import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import React, { PureComponent } from "react";
import classNames from "classnames";
import HeaderService from "./classes/HeaderService";
import RuntimeHandleDataService from "./classes/RuntimeHandleDataService";
import { HyperFormula } from "hyperformula";
import TagService from "./classes/TagService";
import GridService from "./classes/GridService";
import FormulaService from "./classes/FormulaService";
import { cpasDefaultRender, cpasNumericRender } from "./classes/GridRender";
import ReactDOM from "react-dom";
import { clearCpasTableFormula, getCpasTableServerDataByJsonApi, parseFormulaApi, reCalculateNote, filterRuntimeColumnApi, getCpasTableDataByTzTypeAPI, } from "./api/DesignTableApi";
import _ from "lodash";
import HyperFormulaService, { CustomFormulaPlugin, CustomFormulaPluginTranslations, } from "./classes/HyperFormulaService";
import CpasTable from "./";
import { clearCpasTableData, getDsToZlData, parseLogicFormulaData, removeVerifyData, } from "./api/DesignTableApi";
import CpasEditor from "../../components-bs/Editor/index";
import { compareArrays } from "./Tools/index";
import { afterChange, afterColumnResizeHook, afterColumnSortHook, afterOnCellMouseDownHook, afterSelectionEndHook, beforeColumnSortHook, beforePasteHook, cellsHook, compareFunctionFactoryHook, afterDocumentKeyDownHook, } from "./classes/GridHook";
import { convertToNumber, maxNumberLimit, nanoid10, deepClone, MergeType, getHbTypeByZcbfid, transformCrossData, } from "../../tools/Tools";
import { getAllDesignTableApi, getDesignTableInfoByNameApi, getVerifyDataApi, removeCpasTableByName, saveTableApi, saveVerifyData, removeVerifyDataById, } from "./api/DesignTableApi";
import CustomFormulaService from "./classes/CustomFormulaService";
import LogicFormulaService from "./classes/LogicFormulaService";
import ArticulationVerifyService, { artVerifyFormulaType, } from "./classes/ArticulationVerifyService";
import HandSonGridTool from "./HandSonGridTool";
// import Handsontable from "../../../lib/tmp/dist/handsontable.full.min";
import Handsontable from "../../lib/tmp/index";
import { cpasFormulaValidator, cpasTextValidator, } from "./classes/GridValidator";
import { parseDcFormula, parseDrFormula } from "./classes/LogicParse";
import CheckDetailsModal from "./components/Validator/CheckDetails";
import { Modal, Table } from "antd"; //表体默认样式值
//表体默认样式值
export const defaultCellStyle = {
    bl: 1,
    r: {
        type: 1,
        val: 0,
    },
    ht: 2,
    bg: "#fff",
    fc: "#000",
    it: 1,
    fs: 14, // 字号 px
};
export const defaultHeaderStyle = {
    ht: 2,
    bl: 1, //是否加粗 1 不加粗 2加粗
};
const colors = [
    "yellow",
    "red",
    "orange and another color",
    "green",
    "blue",
    "gray",
    "black",
    "white",
    "purple",
    "lime",
    "olive",
    "cyan",
];
/**
 * ## 基于HandsonTable进行改造的二次封装组件
 * ~~~js
 * import CpasTable from  "~/public/cpas-ui/components-ui/components/ExcelGrid"
 * ~~~
 * [HandsonTable连接](https://handsontable.com/docs/javascript-data-grid/)
 *
 * ### 引用注意:
 *
 *  1.由于CpasTable对Handson进行了源码级别的编译。所以必须要手动安装这些依赖。请使用CpasTable的将这几个依赖复制到dependecies中
 *
 * ```
 *      "axios": "^0.27.2",
 *     "hyperformula": "^2.3.0",
 *     "xlsx-js-style": "^1.2.0",
 *     "@types/pikaday": "1.7.4",
 *     "core-js": "^3.0.0",
 *     "dompurify": "^2.1.1",
 *     "moment": "2.29.4",
 *     "numbro": "2.1.2",
 *     "pikaday": "1.8.2"
 * ```
 *
 *  2. 注意React版本要用18
 *
 *  3. 如果有其他异常，请关闭umijs的 msfu
 *
 *  4. 目前是以跑通数据为主要目标，有一些功能不健全并且存在bug。当前阶段只需要关注取数逻辑即可。
 *
 *  5. 如果发现cpas-ui 体积变大不要惊慌，handsontable官方的就48mb。后期我们会针对这进行瘦身
 *
 * ### 功能介绍
 1. CpasTable 是一款支持自定义设计的表格引擎。 表格引擎由前端组件CpasTable + Electron平台后台服务共同实现。 所以在使用CpasTable表格
 时需要启动本地Electron平台。并确保本地数据库中存有CpasTable的表结构。（如果打开界面报504说明本地服务没有启动，可以点击Close关闭错误面板正常使用）
 2. CpasTable 目前针对业务类型划分一共有两种形态，两种形态的差异是取数逻辑不同，包括一些业务交互不一样：
 <br />
 2.1 财务报表类型：fs(依赖于接口动态参数取数方法)，拥有自己配置行列关系的设计方式（取数源中的行列关系设置）。
 <br />
 2.2 披露表类型: ds(依赖于自定义公式，动态行，动态列，单元格取数逻辑)

 ### CpasTable 数据结构介绍

 1. CpasTable数据结构为标准Json格式; 类型声明为 IGridData
 <br />
 ```
 export interface IGridData {
 header: HeadJson[]; //树形复合表头数据结构
 data: any[][]; //二维数组，表格数据
 cellsMeta: any[][]; //单元格设置属性
 tableConfig: any; //表格全局属性
 }
 ```
 <br />
 ```
 {
 "header": [
 {
 "key": "a629c019166140f5a49f19197ec8a9a0",
 "config": { "width": 150, "type": "text", "ht": 2 },
 "label": "项目"
 },
 {
 "key": "7bc94115237e4e14a9eb83831f580db5",
 "config": { "width": 150, "type": "numeric", "ht": 2 },
 "label": "金额"
 },
 {
 "key": "config8d0ae3c30dc342b7a457b4e981191e94",
 "config": { "width": 150, "type": "numeric" },
 "label": "rowConfig"
 }
 ],
 "data": [
 ["固定资产", 0, "{\"rId\":\"e95174d0e0e84c6791159aa1e2a30f12\"}"],
 ["固定资产-其中", 31, "{\"rId\":\"719a0ba85a804ad5a48418974ef99730\"}"]
 ],
 "cellsMeta": [{ "row": 1, "col": 0, "custom": { "r": 2 } }],
 "tableConfig": {}
 }
 ```
 <br />
 2. 字段介绍
 <br />
 2.1 header为表头数据是一个树形结构(Cpas-table支持复合表头), 可参考AntDesign复合表头的数据结构用法
 <br />
 ```
 export interface HeadJson {
 config?: any;
 key: number | string;
 label: string;
 children?: HeadJson[];
 }
 ```
 <br />
 2.2 data为表格的内容信息是一个二维数组，默认最后一列表示配置项。Cpas-table会将其隐藏.注意要区分文本类型和数字类型。文本类型为字符串，数值类型为json数值类型。
 ```
 [
 ["固定资产", 0, "{\"rId\":\"e95174d0e0e84c6791159aa1e2a30f12\"}"],
 ["固定资产-其中", 31, "{\"rId\":\"719a0ba85a804ad5a48418974ef99730\"}"]
 ]
 ```
 <br />
 2.3 cellsMeta为表格单元格粒度样式存储。通常用来描述缩进，字体，对齐方式等单元格粒度样式。 row,col分别表示单元格的索引坐标.
 ```
 目前已知的config配置类型:
 {
 "r": 缩进
 "bl": 粗体
 "w": 权重计算
 "cmap":列映射
 "rmap":行映射
 ....
 }
 "cellsMeta": [{ "row": 1, "col": 0, "custom": { "r": 2 } }],
 ```

 2.4 tableConfig 为表格全局配置. 暂时还未确定

 ### CpasTable confg配置

 CpasTable分为功能性配置以及样式配置. 功能性配置存储在行列配置中. 样式配置存储在IGridData cellMetas中的custom属性。样式配置分为表头配置和表体配置.

  export interface TableConfig{
     tableInfo: Object ;  当前表格的行列信息 {"rowLen":7,"cellLen":35,"columnLen":5,"columnLeafLen":5,"type":"serer"};
     formulaOff : boolean; 断开公式;   公式停止运算
     clearTable : boolean; 清空数据;   公式停止运算
     action : string ;  表示上一次入库的记录从哪里来 .  reCalculate 重算得来 front 前端保存
 }

 ### CpasTable 整理模式confg配置

 export interface ZlTableConfig{
    rowMergeCfg: Object; 行归并条件 {"columnNum": 1,"rowsData": [{"columnNum": 1,"id": "7sDmmb9gLu","value": "aaa","cellData": [],"mergeRowIds": [],"checkedData": []}, {"columnNum": 1,"id": "ACkWBL2iwj","value": "bbb","cellData": [],"mergeRowIds": [],"checkedData": []}],"mergeRow": []}
    sortCfg: Object; 排序条件 {"column_val": "项 目10","sort": "ascend","other_sort": true,"selectColumnNum": 1}
    filterCfg: Object;筛选条件 {"column_val": "期末余额21","order": "front","num": 3,"is_blank_row": true,"is_blank_data_row": true,"selectColumnNum": 2}
    directionCfg：Object; 纸张方向 {"direction": "vertical/horizontal"}
    rule: string; 拆表规则 值参考："1,2",
    dismantleTableMode: boolean 是否拆表 true/false
    hideColumnArr: Arrary, 隐藏列下标[1]
    hideColumnKeyArr: Arrary, 隐藏列rid ["0f271def7ba941b78f311bbfecdb6b77"],
    tableInfo: Object ;  当前表格的行列信息 {"rowLen":7,"cellLen":35,"columnLen":5,"columnLeafLen":5,"type":"serer"};
 }

 1. 行配置(功能)会存储在表格中的最后一个隐藏列(参考CpasTable 数据结构介绍章节).

 ```
 数据格式示例: '{"rId":"e95174d0e0e84c6791159aa1e2a30f12","custom":{"r":3}}' 注意: 这是一个json字符串，需要parse解析才能使用
 ```

 export interface RowConfig{
     "rid" : string ; //主键
     "className" : string; //指定该行独有的样式
     "type": string,  // autocomplete 下拉框数据源模式 ( "visibleRows":10（下拉框显示行数）, "strict":false(下拉框是否开启校验),)
     "r_tag" : string, //行标签
     "r_polymeric" : object // 行聚合运算 e.g.{"type":"SUM","tags":["资产小计"]}
     "w" : string // 'j' 减值运算  'z' 中不参与运算
     “operator_r” : object  //行运算
     "isDynamic" : boolean // 是否动态生成
     "matchDynamic" : boolean ;  // 动态行公式匹配行
 }

 2. 列配置(功能,样式)会存储在每个叶子节点的config中

 ```
 数据格式示例:     "config": { "width": 150, "type": "numeric", "ht": 2 },

 列的样式配置:

 ```
 数据格式
 export interface ColumnConfig{
     "width": number,       // 列宽
     "type": string,  // 列字段类型 text文本  numeric数值 autocomplete 下拉框数据源模式 ( "visibleRows":10（下拉框显示行数）, "strict":false(下拉框是否开启校验),)
     "ht": number  //表头对齐方式 1 左对齐 2居中对齐 3居右对齐
     "validator": string // 该列在前端的文本校验器:
     "matchDynamic" : boolean ;  // 动态行公式匹配行
     "isDynamic" : boolean // 是否动态生成
     "numericFormat" : string ; // 该列的格式化方式, 例如百分比，小数点位数
     "c_tag" : string;  列标签
     "c_polymeric" : object ;  // 聚合运算  e.g. {"type":"SUM","tags":["列合计"]}
     "p_exclude": boolean ; // 是否不参与聚合运算
     "keyword" : boolean ; 是否为合并列 (主键列)
     "className" : string ; 指定该列特有的样式
     "groupId": string, ; 分组模式 （目前用于期间类型功能多个列为一组）
     "timeColumn" : object; // 期间类型  e.g. {"type": "pt","dataId": "2021","valueType": "期末","items": ["2021.12.31","2020.12.31"]
 }
 ```
 3. 单元格样式配置

 ```
 数据格式

 数据格式示例: { "row": 1, "col": 1, "custom": { "ht": 1, "bl": 2 } }

 export interface StyleConfig {
 bl: number; // 是否加粗 1 不加粗 2 加粗
 r: number; // 缩进
 ht: number; // 对齐方式 1 左对齐 2居中对齐 3居右对齐
 bg: string; // 单元格背景颜色
 fc: string; // 字体颜色
 it: number; // 1 常规 、 2 斜体
 fs: number; // 字号 px
 }
 ```




 ### CpasTable API介绍

 CpasTable基于API设计模式细粒度控制内部渲染细节，和DevExpress设计思路一样。例如加载数据不要去直接更改属性值。而是用ref api来进行操作。


 1.  reloadTable(IGridData类型数据) （即上面描述的数据结构）。 重新渲染数据列表
 2.  getCpasTableGrid() 会直接直接返回目前表格的IGridData数据
 3.  saveToServer(p_name?: string, p_type?: string, tid?: string); 保存表到线上  p_name: 表名  p_type:表类型 tid?:表id (如果是披露表类型需要自己传递tid)
 4.  loadTableByServer(name:string,data_id?:string,tid?:string,type?:string):Promise<IGridData> 读取线上数据表并渲染
 5.  getAllDesignTable(); 获取目前线上所有的数据表名称
 6.  removeTableByServer(tid:string) 删除线上数据表
 7.  getCurrentTableMaps() 获取fs类型表格的行列映射关系
 8.  openMenuTools(isShow:boolean); 是否显示设计栏
 9.  openVerifyInfo(isShow:boolean); 是否显示校验详情
 10. setCellData(coords,value); 根据坐标设置单元格值；  coords:{row:number,col:number}
 11. reloadTableData(data:any[][]) 仅重载数据
 12. reRender() 表格重绘. 触发表格重绘
 13. getNodeIndexBySelected()=>number[]; 获取当前选中列
 14. getCurrentColumnSource()=>any[]; 返回当前列的数据源
 15. resetTable(type:string)=>void;   type(fs报表类型,ds披露表类型) 初始化披露表
 16. formulaHandle(formula:string)=>Promise<number> 解析自定义运算公式
 17. formulasListComputed(formulasList:string[])=>Map<string,number> 解析自定义运算公式列表
 */
let cpassRef;
export class HandSonGrid extends PureComponent {
    static MAX_ROWS = 500; // 1 是不计算隐藏行,可以正好在表格显示500行
    static MAX_ROWS_OFFSET = 1;
    static MAX_COLUMNS = 100; // 2 是显示100列,刨除0列和配置列
    static MAX_COLUMNS_OFFSET = 2;
    //默认财务报表数据
    fs_defaultData = () => {
        return [
            [
                "\\",
                "",
                "",
                '{"rId":"' +
                    nanoid10() +
                    "-" +
                    "key" +
                    '","className":"cpas-map-model","type":"autocomplete","visibleRows":10,"strict":true,"source":[]}',
            ],
            ["", "", 0, '{"rId":"' + nanoid10() + '"}'],
        ];
    };
    //默认披露表类型数据
    ds_defaultData = () => {
        return [
            [
                "\\",
                "项目",
                "金额",
                '{"rId":"' +
                    nanoid10() +
                    "-" +
                    "key" +
                    '","className":"cpas-map-model","type":"autocomplete","visibleRows":10,"strict":false,"source":[]}',
            ],
            ["", "", 0, '{"rId":"' + nanoid10() + '"}'],
        ];
    };
    //默认头数据
    fs_defaultHeader = () => {
        return [
            {
                key: nanoid10() + "-key",
                label: "主键",
                config: {
                    //隐藏列配置
                    width: 150,
                    type: "autocomplete",
                    visibleRows: 10,
                    source: [],
                    strict: true,
                    className: "cpas-map-model",
                },
            },
            {
                key: nanoid10(),
                config: {
                    width: 150,
                    type: "text",
                    ht: defaultHeaderStyle.ht,
                    bl: defaultHeaderStyle.bl,
                    keyword: true,
                },
                label: "项目",
            },
            {
                key: nanoid10(),
                config: {
                    width: 150,
                    type: "numeric",
                    ht: defaultHeaderStyle.ht,
                    bl: defaultHeaderStyle.bl,
                    // validator: "cpasFormulaValidator",
                },
                label: "金额",
            },
            {
                key: nanoid10() + "-config",
                config: {
                    width: 150,
                    type: "text",
                },
                label: "rowConfig",
            },
        ];
    };
    ds_defaultHeader = () => {
        return [
            {
                key: nanoid10() + "-key",
                label: "主键",
                config: {
                    //隐藏列配置
                    width: 150,
                    type: "autocomplete",
                    visibleRows: 10,
                    source: [],
                    strict: false,
                    className: "cpas-map-model",
                },
            },
            {
                key: nanoid10(),
                config: {
                    width: 150,
                    type: "text",
                    ht: defaultHeaderStyle.ht,
                    bl: defaultHeaderStyle.bl,
                    keyword: true,
                },
                label: "项目",
            },
            {
                key: nanoid10(),
                config: {
                    width: 150,
                    type: "numeric",
                    ht: defaultHeaderStyle.ht,
                    bl: defaultHeaderStyle.bl,
                    // validator: "cpasFormulaValidator",
                },
                label: "金额",
            },
            {
                key: nanoid10() + "-config",
                config: {
                    width: 150,
                    type: "text",
                },
                label: "rowConfig",
            },
        ];
    };
    tableHeight = 0;
    observer = null; //兼容antd tab写法， 监听dom属性变化
    resizeObserver = null;
    rowHeights = 24;
    columnHeaderHeight = 35;
    //handson页签模式下的最大容错
    maxHeightError = 0;
    // 初始CpasData数据  ------------------------------
    data = null; //表格数据  any[][]
    headerData = []; //header头部信息
    cellMetaData = []; //单元格配置, 加载单元格配置项,仅在保存时和第一次加载时调用
    tableConfig = {}; //全局表格配置
    isInit = false;
    dsSourceData = null; //整理模式下的披露表源数据
    currentDataMaps = {}; // 根据rmap,cmap生成的字典, 用于断开公式后的数据定位.
    rawData = []; //当前节点的源数据（第一次初始化的数据）
    dataSource = "server"; //数据来源方式, 是loadTableByServer 则认定为首次从数据库加载 ,  重算 reCalculate 得来 , 目前依据这个字段, 决定表格单元格取数公式是从dValue中取, 还是取数源中
    cpasTableRefs = []; //拆表后的多实例引用
    memoryClearTable = false;
    //表格是否变动
    tableContentIsChange = false;
    // --------------------------------------------
    // handsontable内部应用 --------------------
    hot; //hanson 引用
    hyper; //hyper公式引用
    manualRowMovePlugin; //行移动插件
    manualColumnMovePlugin;
    persistentStatePlugin;
    manualColumnResize;
    //数据来源  init 初始化 , server 服务端 , import 导入包括json等...
    dataFrom = "init";
    //用于导出记录的zlHeader
    zlHeader = null;
    // --------------------
    //服务类注册----------------------------------------
    tagService; //TagService 维护标签的类
    headerService; //表头数据服务
    runtimeHandleDataService;
    gridService; //表格增删改查服务
    formulaService; //公式服务
    customFormulaService; //勾稽校验服务
    hyperFormulaService; //hyper自定义公式服务
    logicFormulaService; //动态拼装数据公式服务
    articulationVerifyService; //勾稽校验服务
    // --------------------------------------------
    //状态值记录，无需渲染界面的----------------------------------------
    sortLastSource; //手动排序还原
    currentGroupInfo; //分组后的组头位置信息
    actionType = {
        //操作类型，用于在触发cells回调函数时进行逻辑判断
        action: "",
        index: 0,
        amount: 0,
    };
    mapRowsList; //行映射数据源
    mapColumnsList; //列映射数据源
    isShowMaps = false; //是否显示映射状态
    fsTableRef;
    dsTableRef;
    // --------------------------------------------
    // ref声明
    containerRef = React.createRef(); //容器Ref
    menuToolRef; //工具条Ref
    textCanvasRef = React.createRef(); //计算单个文字宽度的内容
    klass;
    //render声明
    cpasDefaultRender;
    cpasNumericRender;
    //Validator验证
    cpasFormulaValidator;
    //hook声明
    beforeColumnSortHook;
    afterOnCellMouseDownHook;
    compareFunctionFactoryHook;
    afterColumnSortHook;
    cellsHook;
    afterColumnResizeHook;
    afterSelectionEndHook;
    afterChange;
    beforePasteHook;
    afterDocumentKeyDownHook;
    currentRecord = null;
    dismantleTableMode;
    constructor(props) {
        super(props);
        /**
         * 构造默认数据,如果props存在。从props中进行加载.否则从default数据中进行加载
         */
        const pGridData = props.gridData;
        this.fsTableRef = props.fsTableRef;
        this.dsTableRef = props.dsTableRef;
        this.klass = classNames({
            "cpas-excel-grid": !this.props.isMultipleTableMode,
            "cpas-excel-grid-multiple": this.props.isMultipleTableMode,
            "cpas-table-type": this.props.type !== "zl",
        }, this.props.className, {});
        if (pGridData) {
            this.data = pGridData.data;
            this.tableConfig = pGridData.tableConfig;
            this.cellMetaData = pGridData.cellsMeta;
            this.headerData = pGridData.header;
        }
        else {
            if (this.props.type === "fs") {
                if (this.props.mapRowsList && this.props.mapRowsList.length === 0) {
                    this.data = this.ds_defaultData(); //TODO 暂时用ds类型表示不校验
                }
                else {
                    this.data = this.fs_defaultData();
                }
                if (this.props.mapColumnsList &&
                    this.props.mapColumnsList.length === 0) {
                    this.headerData = this.ds_defaultHeader(); //TODO  暂时用ds类型表示不校验
                }
                else {
                    this.headerData = this.fs_defaultHeader();
                }
            }
            if (this.props.type === "ds" || this.props.type === "zl") {
                this.data = this.ds_defaultData();
                this.headerData = this.ds_defaultHeader();
            }
        }
        this.state = {
            retract: 0,
            currentRecord: null,
            currentRange: null,
            currentColumnName: "",
            currentColumnType: "",
            isShowFormulaToolBar: false,
            isOpenDetail: false,
            result: [],
            resultList: [],
            topLeftRange: null,
            statistics: {
                sum: 0,
                avg: 0,
                count: 0,
            }, //披露表统计数据
        };
        this.menuToolRef = React.createRef();
        /**
         * hook 绑定
         */
        this.cpasDefaultRender = cpasDefaultRender.bind(this);
        this.cpasNumericRender = cpasNumericRender.bind(this);
        this.cpasFormulaValidator = cpasFormulaValidator.bind(this);
        this.beforeColumnSortHook = beforeColumnSortHook.bind(this);
        this.afterOnCellMouseDownHook = afterOnCellMouseDownHook.bind(this);
        this.compareFunctionFactoryHook = compareFunctionFactoryHook.bind(this);
        this.afterColumnSortHook = afterColumnSortHook.bind(this);
        this.cellsHook = cellsHook.bind(this);
        this.afterColumnResizeHook = afterColumnResizeHook.bind(this);
        this.afterSelectionEndHook = afterSelectionEndHook.bind(this);
        this.afterChange = afterChange.bind(this);
        this.beforePasteHook = beforePasteHook.bind(this);
        this.afterDocumentKeyDownHook = afterDocumentKeyDownHook.bind(this);
    }
    componentDidUpdate(prevProps, prevState) {
        //检测是否显示工具条，进行表格高度重算
        if (prevProps.isShowMenuToolBar !== this.props.isShowMenuToolBar ||
            prevState.isShowFormulaToolBar !== this.state.isShowFormulaToolBar) {
            this.reRender();
        }
        if (this.props.mapRowsList !== prevProps.mapRowsList &&
            this.props.mapRowsList.length !== prevProps.mapRowsList.length //防止调用方不适用useCallback每次都判断为新对象
        ) {
            if (this.props.mapRowsList.length === 0) {
                this.setColumnMapSource(false);
            }
            else {
                this.setColumnMapSource();
            }
        }
        if (this.props.mapColumnsList !== prevProps.mapColumnsList &&
            this.props.mapColumnsList.length !== prevProps.mapColumnsList.length //防止调用方不适用useCallback每次都判断为新对象
        ) {
            if (this.props.mapColumnsList.length === 0) {
                this.setRowMapSource(false);
            }
            else {
                this.setRowMapSource();
            }
        }
        if (this.props.gridData && this.props.gridData !== prevProps.gridData) {
            console.log("gridData change run reloadTable");
            this.reloadTable(this.props.gridData, this.props.type, null, true);
        }
    }
    /**
     * 隐藏显示行列关系
     */
    setRowColumnsMap() {
        this.isShowMaps = !this.isShowMaps;
        this.gridService.hiddenColumnAndRow();
    }
    setColumnMapSource(strict) {
        if (this.hot) {
            const hiddenKey = this.headerService.headerColumn[0]?.key;
            // props 的值发生了改变，在这里进行相应的处理
            this.headerService.updateNodeByKeyAndRefresh({
                source: this.props.mapRowsList,
                strict: strict === undefined,
            }, hiddenKey, true);
            //这里如果被多次重复调用会导致startRow错误
            // TODO 重要bug , 导致cellsMeta重复 会同时出现多个相同坐标的记录
            // this.hot.validateCells();
        }
    }
    setRowMapSource(strict) {
        if (this.hot) {
            this.gridService.setRowConfig(0, {
                source: this.props.mapColumnsList,
                strict: strict === undefined,
            });
            //这里如果被多次重复调用会导致startRow错误
            // TODO 重要bug , 导致cellsMeta重复 会同时出现多个相同坐标的记录
            // 暂时先注释上
            // this.hot.validateCells();
        }
    }
    componentWillReceiveProps(nextProps, nextContext) { }
    shouldInit(mutation) {
        return (mutation.attributeName == "class" &&
            mutation.target.classList.contains("ant-tabs-tabpane-active"));
    }
    findTabPanelActive(el, level) {
        let isFind = false;
        let levelLength = 50;
        let index = 0;
        let currentLevel = 0;
        let lastParent = el;
        if (lastParent.tagName === "BODY") {
            return null;
        }
        while (!isFind && index <= levelLength) {
            if (!lastParent) {
                return null;
            }
            if (lastParent.classList &&
                lastParent.classList.contains("ant-tabs-tabpane")) {
                ++currentLevel;
                if (level === currentLevel) {
                    isFind = true;
                    return lastParent;
                }
            }
            lastParent = lastParent.parentElement;
            index++;
        }
        return null;
    }
    debouncedResize = _.debounce(this.handsonTableResize, 300);
    handsonTableResize() {
        if (this.hot) {
            console.log("重置Resize refreshDimensions");
            try {
                this.hot.refreshDimensions();
            }
            catch (e) {
                console.warn("refreshDimensions异常", e);
            }
        }
    }
    componentDidMount() {
        //监听resize
        if (!this.resizeObserver) {
            this.resizeObserver = new ResizeObserver((entries) => {
                // 当元素的大小发生变化时，会触发回调函数
                for (let entry of entries) {
                    // const { width, height } = entry.contentRect;
                    this.debouncedResize();
                }
            });
            this.resizeObserver.observe(this.containerRef.current);
        }
        //如果是tab
        if (this.props.tabGroup) {
            // console.log(
            //   "--------------检测到 tabGroup 开启 MutationObserver ------------------"
            // );
            this.observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    if (this.shouldInit(mutation)) {
                        // console.log(`检测到需要更新的mutation:`);
                        // console.log(mutation);
                        this.reRender();
                    }
                });
            });
            const activeTabEl = this.findTabPanelActive(this.containerRef.current, 1);
            // console.log(`捕获到1层:`);
            // console.log(activeTabEl);
            //ant-tabs-tabpane
            if (this.containerRef.current) {
                if (activeTabEl) {
                    this.observer.observe(activeTabEl, {
                        attributes: true,
                    });
                }
            }
            if (this.props.tabLevel && this.props.tabLevel > 1) {
                const activeTopTabEl = this.findTabPanelActive(this.containerRef.current, 2);
                console.log(`捕获到2层:..LZC`);
                console.log(activeTopTabEl);
                if (activeTopTabEl) {
                    this.observer.observe(activeTopTabEl, {
                        attributes: true,
                    });
                }
            }
            if (this.props.tabLevel && this.props.tabLevel > 2) {
                const activeTopTabEl = this.findTabPanelActive(this.containerRef.current, 3);
                console.log(`捕获到3层:`);
                console.log(activeTopTabEl);
                if (activeTopTabEl) {
                    this.observer.observe(activeTopTabEl, {
                        attributes: true,
                    });
                }
            }
        }
        if (this.containerRef.current) {
            this.init(this.containerRef.current);
        }
        else {
            console.error("未检测到容器");
        }
    }
    componentWillUnmount() {
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
            this.resizeObserver = null;
        }
        if (this.hot) {
            //销毁公式引擎
            this.hyperFormulaService.destroy();
            this.hyperFormulaService = null;
            this.tagService.destroy();
            this.tagService = null;
            this.gridService.destroy();
            this.gridService = null;
            this.formulaService.destroy();
            this.formulaService = null;
            this.headerService.destroy();
            this.headerService = null;
            this.articulationVerifyService.destroy();
            this.articulationVerifyService = null;
            this.logicFormulaService.destroy();
            this.logicFormulaService = null;
            //检测是否被HyperFormulaService中所持有;
            const registerGridRef = HyperFormulaService.registerGridRef;
            for (let i = registerGridRef.length - 1; i >= 0; i--) {
                const ref = registerGridRef[i];
                //对比引用相同则删除
                if (ref === this) {
                    console.log(`type:${this.props.type} name:${this.props.name} componentWillUnmount : HyperFormulaService.registerGridRef`);
                    HyperFormulaService.registerGridRef.splice(i, 1);
                }
            }
            console.log(`type:${this.props.type} name:${this.props.name} componentWillUnmount : 销毁CpasTable`);
            this.hot.destroy();
            console.log(`type:${this.props.type} name:${this.props.name} componentWillUnmount : 销毁Hyper`);
            this.hyper.destroy();
            //销毁拆表
            this.cpasTableRefs.forEach((ref) => {
                if (ref.current) {
                    ref.current.unmount();
                }
            });
            this.cpasTableRefs = [];
            if (this.observer) {
                console.log(`type:${this.props.type} name:${this.props.name} componentWillUnmount : 销毁observer`);
                this.observer.disconnect();
                this.observer = null;
            }
        }
    }
    /**
     * 设置表格内容状态是否改变
     */
    setTableContentChange(isChange, handleLog) {
        this.tableContentIsChange = isChange;
        // TODO handleLog 记录操作日志,暂时不做. 内存中维护操作日志栈。
        console.log(`操作类型:${handleLog.type} 操作参数${JSON.stringify(handleLog.params)} 操作数据状态:${this.getCpasTableGrid("source")}`);
    }
    async init(container) {
        console.log("--------------------执行init-----------------------");
        const type = this.props.type;
        //如果是外部传入的数据，先进行一次重算。再进行赋值 innerTable 弹窗中的CpasTable表格， 单元格取数和勾稽取数
        if (this.props.gridData &&
            type !== "zl" &&
            this.props.name !== "innerTable") {
            const response = await reCalculateNote(this.props.gridData);
            if (response && response.data) {
                const gridData = response.data;
                this.data = gridData.data;
                this.headerData = gridData.header;
                this.cellMetaData = gridData.cellsMeta;
                this.tableConfig =
                    typeof gridData.tableConfig === "string"
                        ? JSON.parse(gridData.tableConfig)
                        : gridData.tableConfig;
            }
        }
        /**
         * 初始化tableConfig表头状态
         */
        // this.menuToolRef.current?.updateTableConfigToolsState(this.tableConfig);
        this.actionType = {
            action: "load",
            index: 0,
            amount: 0,
        };
        //初始化表头数据
        this.headerService = new HeaderService(this);
        this.runtimeHandleDataService = new RuntimeHandleDataService(this);
        this.headerService.headerCompute(this.headerData);
        //初始化TagService类
        this.tagService = new TagService(this);
        //初始化表格服务
        this.gridService = new GridService(this);
        //初始化公式服务
        this.formulaService = new FormulaService(this);
        //初始化勾稽校验公式服务
        this.customFormulaService = new CustomFormulaService();
        //初始化Hyper自定义公式服务
        this.hyperFormulaService = new HyperFormulaService();
        //初始化行公式服务
        this.logicFormulaService = new LogicFormulaService(this);
        //注册动态行公式
        this.logicFormulaService.registerFormula("Dr", parseDrFormula);
        //注册动态列公式
        this.logicFormulaService.registerFormula("Dc", parseDcFormula);
        //初始化勾稽校验
        this.articulationVerifyService = new ArticulationVerifyService(this);
        //执行逻辑公式
        // try {
        //   const logicGridData =
        //     await this.logicFormulaService.scanAndExecuteAllFormula();
        //   //重置化表格数据
        //   if (logicGridData) {
        //     this.gridService.resetGridData(logicGridData);
        //   }
        // } catch (e) {
        //   throw e;
        // }
        // const container = document.getElementById(this.props.container);
        /**
         * 自定义单元格取数公式
         */
        HyperFormula.registerFunctionPlugin(CustomFormulaPlugin, CustomFormulaPluginTranslations);
        if (this.props.formulaTimeSlice === true) {
            HyperFormulaService.registerGridRef.push(this);
        }
        // create an external HyperFormula instance
        //注入HyperFormula实例  用于自定义公式 以及  勾稽校验
        const nullDateCpas = { year: 1900, month: 1, day: 1, gridRef: this };
        const hyperformulaInstance = HyperFormula.buildEmpty({
            // to use an external HyperFormula instance,
            // initialize it with the `'internal-use-in-handsontable'` license key
            licenseKey: "internal-use-in-handsontable",
            nullDate: nullDateCpas,
        });
        this.hyper = hyperformulaInstance;
        Handsontable.renderers.registerRenderer("cpasDefaultRender", this.cpasDefaultRender);
        Handsontable.renderers.registerRenderer("cpasNumericRender", this.cpasNumericRender);
        Handsontable.validators.registerValidator("cpasFormulaValidator", cpasFormulaValidator);
        Handsontable.validators.registerValidator("text", cpasTextValidator);
        if (!this.containerRef.current) {
            console.log("-------------cpas table init 没有获取到dom元素----------------");
            return;
        }
        const hot = new Handsontable(container, {
            nestedHeaders: this.headerService.data,
            data: this.data,
            name: this.props.name,
            // rowHeaders: true,
            rowHeaders: function (visualRowIndex) {
                // console.log(visualRowIndex);
                return `${visualRowIndex + 1}`;
            },
            afterContextMenuShow: (context) => {
                const [row, col] = context.hot.getSelectedLast();
                if (row < 0 || col < 0) {
                    return;
                }
                const cellMeta = context.hot.getCellMeta(row, col);
                if (!(cellMeta.custom && cellMeta.custom.beVerified)) {
                    context.close();
                }
            },
            contextMenu: this.props.afterOnArtCellClick
                ? {
                    callback: (key, selection, clickEvent) => {
                        // Common callback for all options
                        console.log("被校验详情art", this.props, key, selection, clickEvent, this.articulationVerifyService.artParseResultList);
                        const selectionDefault = selection[0]; // 勾稽只取第一个，只支持单个查看
                        const { start } = selectionDefault;
                        if (key === "art") {
                            if (this.props.afterOnArtCellClick) {
                                const result = this.articulationVerifyService.getBeVerifiedItemByCoords(start);
                                console.log("被校验详情", result);
                                this.props.afterOnArtCellClick(clickEvent, start, result);
                            }
                        }
                    },
                    items: {
                        art: {
                            name: "被校验详情",
                        },
                    },
                }
                : false,
            manualColumnResize: true,
            afterGetColHeader: (visualColumnsIndex, TH) => {
                // console.log(TH);
                // TH.innerHTML =
                //   '<div class="cpas-table-header-middle relative"><span class="colHeader columnSorting sortAction">C-金额123123123123123123123123312</span></div>';
            },
            readOnly: this.props.model && this.props.model === "read",
            colHeaders: true,
            // autoColumnSize: true,
            colWidths: 150,
            // autoWrapRow: true,
            // manualRowResize: true,
            comments: {
                // @ts-ignore
                readOnly: true,
            },
            columnHeaderHeight: this.columnHeaderHeight,
            rowHeights: this.rowHeights,
            className: "cpas_table",
            currentHeaderClassName: "ht__highlight",
            height: this.props.height || "100%",
            persistentState: true,
            // height: () => {
            //   console.log(this)
            //   return 500;
            // },
            width: "auto",
            // width: 500,
            // height: 500,
            // rowHeaderWidth: 100,  //设置序号那一列的宽度
            maxRows: HandSonGrid.MAX_ROWS + HandSonGrid.MAX_ROWS_OFFSET,
            maxCols: HandSonGrid.MAX_COLUMNS + HandSonGrid.MAX_COLUMNS_OFFSET,
            viewportColumnRenderingOffset: HandSonGrid.MAX_COLUMNS + HandSonGrid.MAX_COLUMNS_OFFSET,
            viewportRowRenderingOffset: HandSonGrid.MAX_ROWS + HandSonGrid.MAX_ROWS_OFFSET,
            manualRowMove: true,
            // manualColumnMove: true,
            manualColumnFreeze: true,
            // beforeColumnSort: this.beforeColumnSortHook,  //TODO 刷公式排序需要解开
            // afterColumnSort: this.afterColumnSortHook, //TODO 刷公式排序需要解开
            // columnSorting: {
            //   sortEmptyCells: false, // true = the table sorts empty cells, false = the table moves all empty cells to the end of the table (by default)
            //   indicator: true, // true = shows indicator for all columns (by default), false = don't show indicator for columns
            //   // headerAction: true, // true = allow to click on the headers to sort (by default), false = turn off possibility to click on the headers to sort
            //   // @ts-ignore
            //   compareFunctionFactory: this.compareFunctionFactoryHook, //TODO 刷公式排序需要解开
            // },
            hiddenColumns: {
                // set columns that are hidden by default
                columns: [0, this.headerService.lastHeader],
            },
            hiddenRows: {
                rows: [0],
            },
            afterRender: (isForced) => {
                console.log(`after render ${isForced}`);
            },
            afterOnCellCornerDblClick: (event) => {
                console.log(event);
            },
            beforeSetRangeEnd: (coords) => {
                // 如果选中的最后范围包括最后一列, 则跳过
                // 对应bug选中行,delete会将隐藏列的内容也删除掉
                const { col } = coords;
                const lastHeader = this.headerService.lastHeader;
                if (col === lastHeader) {
                    coords.col = coords.col - 1;
                }
            },
            afterChange: this.afterChange,
            beforeChange: (changes, index) => {
                changes.forEach((item, index) => {
                    const [rowIndex, columnIndex] = item;
                    const valueType = this.headerService.headerColumn[columnIndex].config.type;
                    if (valueType === "numeric") {
                        //检测货币符号转换
                        const convert_number = convertToNumber(changes[index][3]);
                        //控制最大数值
                        const handle_number = maxNumberLimit(convert_number);
                        changes[index][3] = handle_number;
                    }
                });
            },
            beforeViewRender: (isForced, skipRenderObj) => {
                console.log(isForced, skipRenderObj, "beforeViewRender");
                const containerEl = this?.containerRef?.current;
                if (containerEl) {
                    const { width, height } = containerEl.getBoundingClientRect();
                    if (width === 0 || height === 0) {
                        skipRenderObj.skipRender = true;
                    }
                    else {
                        skipRenderObj.skipRender = false;
                    }
                }
            },
            beforePaste: this.beforePasteHook,
            // beforeKeyDown: this.beforeKeyDownHook,
            afterDocumentKeyDown: this.afterDocumentKeyDownHook,
            afterRefreshDimensions: (previousDimensions, currentDimensions, stateChanged) => {
                if (stateChanged) {
                    const $parentHeight = this.containerRef.current.parentElement.getBoundingClientRect()
                        .height;
                    this.tableHeight = $parentHeight;
                    this.reRender(); // 重置高度
                }
            },
            beforeValidate(value, row, prop, source) {
                // console.log(value, row, prop, source);
            },
            afterValidate: (isValid, value, row, prop) => {
                // console.log(hot.getCellMeta(row, prop));
                // console.log(isValid);
                // console.log(row);
                // console.log(`afterValidate 校验值${value}`);
                if (this.hot) {
                    const cellMeta = this.hot.getCellMeta(row, prop);
                    // console.log(`afterValidate cellMeta`);
                    // console.log(cellMeta);
                    if (cellMeta["fv"] !== undefined) {
                        return cellMeta["fv"];
                    }
                }
                if (value === "...") {
                    //异步计算过程
                    return true;
                }
                return isValid;
            },
            afterCreateCol: (data, coords) => {
                console.log("检测到新列插入，更新 this.data");
                this.data = this.hot.getSourceData();
            },
            afterCreateRow: (index, amount) => {
                console.log("检测到新行插入，更新 this.data");
                this.data = this.hot.getSourceData();
            },
            afterColumnMove: (movedColumns, finalIndex, dropIndex, movePossible, orderChanged) => {
                console.log("检测到移动列");
                this.data = this.hot.getSourceData();
            },
            afterRowMove: (movedRows, finalIndex, dropIndex, movePossible, orderChanged) => {
                console.log("检测到移动行");
                this.data = this.hot.getSourceData();
            },
            afterRemoveRow: (index, amount, physicalRows) => {
                console.log("检测到删除行，更新 this.data");
                this.data = this.hot.getSourceData();
            },
            afterRemoveCol: (index, amount, physicalColumns) => {
                // 这个hook不会调用,删除列走手动控制数据方式
                console.log("检测到删除列，更新 this.data");
                this.data = this.hot.getSourceData();
            },
            afterUpdateData: (sourceData, initialLoad, source) => {
                this.data = this.hot.getSourceData();
            },
            outsideClickDeselects(event) {
                //todo 何时取消全部选择，暂时不取消。
                return false;
            },
            beforeRemoveCellClassNames: () => {
                return undefined;
            },
            afterOnCellMouseOver: (event, coords, TD) => {
                if (this.props.afterOnCellMouseOver) {
                    this.props.afterOnCellMouseOver(event, coords, TD);
                }
            },
            cells: this.cellsHook,
            undo: true,
            licenseKey: "non-commercial-and-evaluation",
            formulas: {
                engine: hyperformulaInstance,
                // @ts-ignore
                sheetName: "main",
                namedExpressions: [
                    {
                        name: "ADDITIONAL_COST",
                        expression: 100,
                    },
                ],
            },
            // afterFormulasValuesUpdate: (changes) => {
            //   //公式运算
            //   changes.forEach((change: any) => {
            //     if (change.address.row !== 0 && change.address.col !== 0) {
            //       // console.log("change", change.address, change.newValue);
            //       change.newValue = 100;
            //     }
            //   });
            // },
            afterColumnResize: this.afterColumnResizeHook,
            afterOnCellMouseDown: this.afterOnCellMouseDownHook,
            afterSelectionEnd: this.afterSelectionEndHook,
        });
        //初始化hot
        this.hot = hot;
        this.manualRowMovePlugin = this.hot.getPlugin("manualRowMove");
        this.manualColumnMovePlugin = this.hot.getPlugin("manualColumnMove");
        this.persistentStatePlugin = this.hot.getPlugin("persistentState");
        this.manualColumnResize = this.hot.getPlugin("manualColumnResize");
        this.isInit = true;
        //hot instance中挂载组件实例， 用于获取不到 HandsonGrid的hooks中。 如验证器
        hot["ref"] = this;
        this.actionType = {
            action: "",
            index: 0,
            amount: 0,
        };
        //如果初始化时没有高度，尝试等待重新渲染
        if (!this.checkParentHeight()) {
            // console.log("父容器没有高度,尝试等待重新渲染");
            this.reRender();
        }
        //如果是外部传入数据，初始化默认刷新一次公式.
        // if (this.props.gridData && type !== "zl") {
        //   this.formulaService.refreshAllPolymericRow();
        //   this.formulaService.refreshAllPolymericColumn();
        // }
    }
    resetState(obj) {
        this.setState({
            ...this.state,
            ...obj,
        });
    }
    /**
     * 设置单元格样式
     */
    setCellData(coords, value) {
        const { row, col } = coords;
        if (row > -1 && col > -1) {
            this.hot.setDataAtCell(row, col, value);
        }
    }
    /**
     * 计算文字宽度
     */
    getTextWidth(font) {
        if (this.textCanvasRef.current) {
            const ctx = this.textCanvasRef.current.getContext("2d");
            ctx.font = "13px -apple-system";
            const txt = "田";
            return ctx.measureText(txt).width;
        }
        else {
            return 14;
        }
    }
    /**
     * 表格重绘
     */
    reRender() {
        if (this.hot) {
            //官方示例中给出的延迟渲染的方法
            //http://jsfiddle.net/x910e6zm
            if (!this.checkParentHeight() && this.maxHeightError < 5) {
                setTimeout(() => {
                    this.reRender();
                    this.maxHeightError++;
                }, 20);
            }
            else {
                console.log("reRender Height");
                setTimeout(() => {
                    this.hot.render();
                }, 20);
            }
        }
    }
    /**
     * 检测当前父容器高度
     */
    checkParentHeight() {
        const containerDom = this.containerRef.current;
        if (this.props.height)
            return;
        if (containerDom) {
            return containerDom.getBoundingClientRect().height;
        }
        else {
            return 0;
        }
    }
    getCurrentColumnSource() {
        return this.headerService.headerColumn;
    }
    //重算逻辑公式，单元格公式。重新渲染表格
    async reCalculateFormula(callback, isrReCalculateArt = true, zlArtVerifyFormulaList = null) {
        this.dataSource = "reCalculate";
        //清空前端缓存
        await this.hyperFormulaService.clearCache();
        //解开清空数据状态
        this.tableConfig["clearTable"] = false;
        this.memoryClearTable = false;
        //如果断开公式连接，不执行重算
        if (this.tableConfig["formulaOff"]) {
            return;
        }
        //获取当前表格数据
        const gridData = this.getCpasTableGrid();
        //1. 检测期间类型，执行期间类型标记运算
        let response;
        response = await reCalculateNote(gridData);
        if (response.code === 500 || response.code === "500") {
            this.menuToolRef.current?.updateTableConfigToolsState(this.tableConfig);
            console.warn("重算接口失败");
            return;
        }
        const reCalculateData = response.data;
        //重新渲染表格,重新渲染后会触发自定义公式重算.
        //清空单元格公式缓存
        await this.hyperFormulaService.clearCache();
        await this.reloadTable(reCalculateData, null, null, true);
        // //刷新行列公式
        // this.formulaService.refreshAllPolymericRow();
        // this.formulaService.refreshAllPolymericColumn();
        setTimeout(() => {
            this.hot.render();
        }, 200);
        //执行勾稽公式重算
        //执行勾稽重算
        if (isrReCalculateArt) {
            let verifyData = null;
            const artFormulaList = zlArtVerifyFormulaList && zlArtVerifyFormulaList.length
                ? zlArtVerifyFormulaList
                : this.articulationVerifyService.artVerifyFormulaList;
            if (artFormulaList.length > 0) {
                verifyData = await this.articulationVerifyService.parseArtVerifyFormula(artFormulaList);
            }
            if (callback) {
                callback(verifyData);
            }
        }
        this.setTableContentChange(true, {
            type: "重算",
            params: null,
        });
    }
    //恢复逻辑公式初始状态
    async resetLogicFormulaState() {
        //获取当前表格数据
        const currentGridData = this.getCpasTableGrid();
        //1. 重算逻辑公式
        //1.1. 裁剪掉动态数据
        // const afterTrimGridData =
        //   this.logicFormulaService.trimAllDynamicRowsOrColumns(gridData, true);
        const afterTrimGridData = await parseLogicFormulaData("remove", currentGridData);
        await this.reloadTable(afterTrimGridData.data, null, null, true);
        this.setTableContentChange(true, {
            type: "重置行列公式",
            params: null,
        });
    }
    /**
     * 重载CpasTable整体结构
     * @param tableData
     */
    async reloadTable(tableData, type, dsSourceData, isStopRunLogic, //是否运行逻辑公式
    isReset // 是否重置状态
    ) {
        // const { header, data, cellsMeta, tableConfig } = tableData;
        // 整理模式下不运行逻辑公式检测，运算
        if (this.persistentStatePlugin) {
            this.persistentStatePlugin.resetValue();
        }
        // const { header, data, cellsMeta, tableConfig } =
        //   this.props.type === "zl" || isStopRunLogic === true //逻辑公式触发重载，和整理模式下不触发逻辑公式逻辑
        //     ? tableData
        //     : await this.logicFormulaService.scanAndExecuteAllFormula(tableData);
        let { header, data, cellsMeta, tableConfig } = tableData;
        if (!tableConfig) {
            throw new Error("未解析到tableConfig");
        }
        if (typeof tableConfig === "string") {
            //尝试解析一次
            try {
                const parseTableConfig = JSON.parse(tableConfig);
                //如果经过解析一次还未解析正确则抛出错误
                if (typeof parseTableConfig === "string") {
                    throw new Error("tableConfig格式错误");
                }
                if (typeof parseTableConfig === "object") {
                    this.tableConfig = parseTableConfig;
                }
            }
            catch (e) {
                throw new Error("tableConfig格式错误");
            }
        }
        else if (typeof tableConfig === "object") {
            this.tableConfig = tableConfig;
        }
        if (this.props.type !== "zl" &&
            isStopRunLogic !== true &&
            tableConfig["formulaOff"] !== true &&
            this.props.name !== "innerTable") {
            const reCalculateResponse = await reCalculateNote(tableData);
            if (reCalculateResponse.code !== 500) {
                const reCalculateData = reCalculateResponse.data;
                header = reCalculateData.header;
                data = reCalculateData.data;
                cellsMeta = reCalculateData.cellsMeta;
                tableConfig = reCalculateData.tableConfig;
                this.tableConfig["clearTable"] = false;
                this.tableConfig["action"] = "reCalculate";
            }
        }
        //整理模式下每次要将ds的数据源同步过来;
        if (dsSourceData) {
            this.dsSourceData = _.cloneDeep(dsSourceData);
        }
        this.data = data;
        this.headerData = header;
        this.actionType = {
            action: "load",
            index: 0,
            amount: 0,
        };
        this.cellMetaData = cellsMeta;
        if (tableConfig && tableConfig.isGroup) {
            this.menuToolRef.current.currentGroupKeyColumnChange(tableConfig.currentGroupKeyColumn);
        }
        this.headerService.headerCompute(header, false);
        /**
         * 提前将data数据转换成config 避免cellHooks中造成重复渲染
         */
        // this.data.forEach((row) => {
        //   const config_row = row[this.headerService.lastHeader];
        //   if (typeof config_row === "string") {
        //     row[this.headerService.lastHeader] = config_row
        //       ? JSON.parse(config_row)
        //       : {};
        //   }
        // });
        // loadCellMeta(cellsMeta);
        //TODO:这里有优化空间，loadData和hiddenColumnAndRow分别触发了一次重新渲染。
        // this.filterTrimRmapCmap(data);
        const { fixedColumnsStart, showRowTag } = this.tableConfig;
        this.hot.suspendRender();
        try {
            this.hot.loadData(this.data);
            this.gridService.hiddenColumnAndRow();
            // 运行时配置判断
            if (fixedColumnsStart) {
                this.hot.updateSettings({ fixedColumnsStart: fixedColumnsStart + 1 });
            }
            if (this.props.mapColumnsList && this.props.mapColumnsList.length === 0) {
                this.setColumnMapSource(false);
            }
            else {
                this.setColumnMapSource();
            }
            if (this.props.mapRowsList && this.props.mapRowsList.length === 0) {
                this.setRowMapSource(false);
            }
            else {
                this.setRowMapSource();
            }
        }
        catch (e) {
            throw e;
        }
        finally {
            this.hot.resumeRender();
        }
        // if (type !== "zl") {
        //   this.formulaService.refreshAllPolymericRow();
        //   this.formulaService.refreshAllPolymericColumn();
        // }
        this.actionType = {
            action: "",
            index: 0,
            amount: 0,
        };
        this.menuToolRef.current?.updateTableConfigToolsState(this.tableConfig);
        if (showRowTag && this.props.type !== "zl") {
            await this.tagService.isShowTagColumn(true, this, true);
        }
        if (isReset) {
            //清空统计状态
            this.hot.deselectCell();
            this.setState({
                statistics: {
                    sum: 0,
                    avg: 0,
                    count: 0,
                },
            });
        }
        /**
         * 如果存在公式则进行结果标注
         */
        console.log("执行勾稽校验标注");
        const verifyResult = transformCrossData(this.articulationVerifyService.artParseResultList);
        //fs类型默认不标记， 因为会和公式颜色冲突.
        if (verifyResult.length > 0 && this.props.type !== "ds") {
            this.articulationVerifyService.batchMarkBeVerifiedItem(verifyResult);
        }
        let cpasData;
        cpasData = { header, data, cellsMeta, tableConfig };
        // 用户导入json文件时执行一次
        const userAction = localStorage.userAction;
        if (userAction === "clickedImport") {
            this.runtimeHandleDataService.recoverSession(cpasData);
            localStorage.removeItem("userAction");
        }
    }
    /**
     * 断开公式连接
     */
    triggerDisconnectFormula() {
        if (!this.menuToolRef.current) {
            return;
        }
        const formulaOff = !this.menuToolRef.current.state.formulaOff;
        this.tableConfig["formulaOff"] = formulaOff;
        this.menuToolRef.current.setState({
            formulaOff: formulaOff,
        });
    }
    /**
     * 清空公式
     */
    async clearFormula() {
        const currentSourceGridData = this.getCpasTableGrid();
        const currentDisplayGridData = this.getCpasTableGrid("display");
        let result;
        try {
            result = await clearCpasTableFormula(currentSourceGridData, currentDisplayGridData.data);
        }
        catch (e) {
            throw e;
        }
        if (result.data) {
            await this.reloadTable(result.data, null, null, true);
        }
    }
    /**
     * 根据范围计算统计数值
     * @param startRow
     * @param starColumn
     * @param endRow
     * @param endColumn
     * @param selectionLayerLevel
     */
    statisticsByRange = (statistics) => {
        this.setState({
            ...statistics,
        });
    };
    /**
     * 清空非公式数据
     */
    async clearTableData() {
        this.tableConfig["clearTable"] = true;
        // 如果在编辑状态进行, 状态清空. 不能依赖于库里的dValue状态(针对于单元格取数的情况. 所以这里增加一个 memoryClearTable标记)
        this.memoryClearTable = true;
        const currentSourceGridData = this.getCpasTableGrid();
        const currentDisplayGridData = this.getCpasTableGrid("display");
        let result;
        try {
            result = await clearCpasTableData(currentSourceGridData, currentDisplayGridData.data);
        }
        catch (e) {
            throw e;
        }
        if (result.data) {
            await this.reloadTable(result.data, null, null, true);
        }
    }
    /**
     * rmap,cmap去空格
     */
    filterTrimRmapCmap(data) {
        for (let i = 0; i < data.length; i++) {
            const row = data[i];
            for (let j = 0; j < row.length; j++) {
                if (i === 0 || j === 0) {
                    if (data[i][j]) {
                        data[i][j] = data[i][j].trim();
                    }
                }
            }
        }
    }
    /**
     * 重载数据
     * @param data
     */
    reloadTableData(data) {
        this.hot.loadData(data);
        // this.formulaService.refreshAllPolymericRow();
        // this.formulaService.refreshAllPolymericColumn();
    }
    /**
     * 附带样式重载数据
     */
    reloadTableDataWithStyle(data, refreshCellsMetaInfo) {
        //提取当前cellsMeta
        let cellsMetaConfig = this.filterMetas();
        this.hot.loadData(data);
        this.data = data;
        this.actionType = {
            action: "load",
            index: 0,
            amount: 0,
        };
        if (refreshCellsMetaInfo) {
            const { type, start, end } = refreshCellsMetaInfo;
            if (type === "column") {
                cellsMetaConfig = this.gridService.refreshCellsMetaByColumn("add", start, end - start, cellsMetaConfig, false //是否拷贝样式
                );
            }
            else if (type === "row") {
                cellsMetaConfig = this.gridService.refreshCellsMetaByRow("add", start, end - start, cellsMetaConfig, false //是否拷贝样式
                );
            }
        }
        this.cellMetaData = cellsMetaConfig;
        this.hot.render();
        this.actionType = {
            action: "",
            index: 0,
            amount: 0,
        };
    }
    /**
     * 重置表格到初始化模式
     * @param type fs 报表类型  ds披露表类型
     * isClearTableConfig 决定是否只清空数据，不清空表格配置
     */
    async resetTable(type, isClearTableConfig) {
        let defaultTableData = {
            header: null,
            data: null,
            cellsMeta: null,
            tableConfig: null,
        };
        if (type === "fs") {
            defaultTableData = {
                header: this.fs_defaultHeader(),
                data: this.fs_defaultData(),
                cellsMeta: [],
                tableConfig: isClearTableConfig ? {} : this.tableConfig,
            };
        }
        else {
            defaultTableData = {
                header: this.ds_defaultHeader(),
                data: this.ds_defaultData(),
                cellsMeta: [],
                tableConfig: isClearTableConfig ? {} : this.tableConfig,
            };
        }
        this.hot.deselectCell();
        this.setState({
            currentRecord: null,
            currentRange: null,
        });
        //清空内存级别的清空数据状态
        this.memoryClearTable = false;
        //清空状态记录保存
        this.persistentStatePlugin.resetValue();
        //清空勾稽公式
        this.articulationVerifyService.artVerifyFormulaList = [];
        this.articulationVerifyService.artParseResultList = [];
        this.articulationVerifyService.clearArtVerifyMark();
        this.dataFrom = "init";
        await this.reloadTable(defaultTableData, null, null, true);
    }
    /**
     * 获取当前表格内的 IGridData信息
     */
    getCpasTableGrid(data_type, isContextData, isCellsMetaNeed) {
        const sheetId = this.hyper?.getSheetId("main");
        const d = this.hyper?.getSheetDimensions(sheetId);
        //todo 如果排序了， 则获取一遍 getData 重新赋值到 sourceData . 将改动后的visualData转换为真实data存储
        // console.log(hyper.current.getConfig());
        // console.log("hyper中的数据:");
        // console.log(this.hyper.getAllSheetsSerialized());
        // console.log("hyper中的命名公式:");
        // console.log(this.hyper.getAllNamedExpressionsSerialized());
        // console.log("列头数据:");
        // console.log(this.headerService.headJson);
        // console.log("最后子列表头:");
        // console.log(this.headerService.headerColumn);
        // console.log("关键列索引");
        // console.log(this.headerService.getKeywordColumnIndex());
        // console.log("表数据 getData 获取排序等数据转换后的数据 visual");
        // console.log(this.hot.getData());
        // console.log("单元格配置信息");
        // console.log(this.hot.getCellsMeta());
        // console.log("表数据 getSourceData 获取源数据 physical ");
        // console.log(this.hot.getSourceData());
        // console.log("html");
        // console.log(this.hot.toHTML());
        // console.log("table");
        // console.log(this.hot.toTableElement());
        // console.log("maps");
        // console.log(this.getCurrentTableMaps());
        //TODO 行列配置source过滤
        const exportHeadJson = this.headerService?.headJson
            ? JSON.parse(JSON.stringify(this.headerService?.headJson))
            : undefined;
        if (exportHeadJson) {
            exportHeadJson[0].config.source = [];
        }
        let data = null;
        if (data_type === "display" && this.hot) {
            data = this.hot.getData();
        }
        else if (isContextData === true) {
            data = this.data;
        }
        else {
            data = this.hot ? this.hot.getSourceData() : this.data;
        }
        let saveObj = {
            header: exportHeadJson,
            data: data,
            cellsMeta: this.filterMetas(isCellsMetaNeed),
            tableConfig: this.tableConfig,
        };
        console.log("saveObj -----------");
        console.log(saveObj);
        return saveObj;
    }
    /**
     * 根据rmap,cmap获取坐标
     */
    getCellCoordsByRmapCmap(rmap, cmap) {
        const w = this.gridService.getCellCoordsByRmapCmap(rmap, cmap);
        console.log("调用服务", w);
        return this.gridService.getCellCoordsByRmapCmap(rmap, cmap);
    }
    /**
     * 过滤Meta信息, 精简
     */
    filterMetas(isCellsMetaNeed = true) {
        const filterCellsMeta = [];
        const cellsMeta = this.hot?.getCellsMeta();
        for (let i = 0; i < cellsMeta?.length; i++) {
            const cellMetaItem = cellsMeta[i];
            // 由于cellsMeta现在要兼任存储额外属性的工作, 所以现在非custom的也要存储出来
            // 额外字段以 attr_ 开头
            // if ((cellMetaItem && cellMetaItem["custom"]) ||
            //     (cellMetaItem && cellMetaItem["v"])) {
            if (cellMetaItem) {
                const cellMetaItemKeys = Object.keys(cellMetaItem);
                const metaSave = {};
                metaSave["row"] = cellMetaItem["row"];
                metaSave["col"] = cellMetaItem["col"];
                if (cellMetaItem["readOnly"]) {
                    metaSave["readOnly"] = cellMetaItem["readOnly"];
                }
                if (cellMetaItem["custom"]) {
                    metaSave["custom"] = this.excludeConfigToServer(cellMetaItem["custom"], isCellsMetaNeed);
                }
                // 字段额外属性
                if (cellMetaItem["v"]) {
                    metaSave["v"] = cellMetaItem["v"];
                    metaSave["fv"] = cellMetaItem["fv"] ? 1 : 0;
                }
                // 注解字段
                if (cellMetaItem["comment"]) {
                    metaSave["comment"] = cellMetaItem["comment"];
                }
                // 将以attr_开头的循环加入到meta信息中
                cellMetaItemKeys.forEach((key) => {
                    if (key.startsWith("attr_")) {
                        metaSave[key] = cellMetaItem[key];
                    }
                });
                filterCellsMeta.push(metaSave);
            }
            // }
        }
        return filterCellsMeta;
    }
    /**
     * 整理模式下运行时解析的CpasTableData数据
     */
    getZlCpasTableGrid(cpasData) {
        //TODO 整理模式下的数据处理
        return cpasData;
    }
    /**
     * 过滤运行时列
     */
    async filterRunTimeColumn(iGridData) {
        return await filterRuntimeColumnApi(iGridData);
    }
    /**
     * serverData 接收CpasDataJson模式的数据进行存储.
     * @param serverData
     * @param name
     * @param type
     * @param tid
     * @param data_id
     * @param aValue
     */
    async saveToServerByCpasData(serverData, name, type, tid, data_id, beforeData = null) {
        serverData = await this.filterRunTimeColumn(serverData);
        const { header, data, cellsMeta, tableConfig, cpasDesc } = serverData;
        const sourceData = data;
        const displayData = data;
        const rowMaps = this.gridService.getAllRowsMaps([...data]);
        const columnMaps = this.headerService.getAllHeaderMap([...data]);
        const headerData = this.headerService.toServerLevelData(header, tid, type);
        const stringTableConfig = tableConfig ? JSON.stringify(tableConfig) : "{}";
        const headerComputeData = this.headerService.headerComputeData(serverData.header);
        const headers = headerComputeData.headerColumn;
        const lastHeader = headerComputeData.lastHeader;
        const params = {
            sourceData,
            displayData,
            beforeData,
            rowMaps,
            columnMaps,
            headerData,
            tableConfig: stringTableConfig,
            headers,
            lastHeader,
            cellsMeta,
            name,
            tid,
            type,
            data_id,
            cpasDesc,
        };
        return await this.saveCpasTable(params);
    }
    /**
     * 从组件中获取数据源进行存储
     * @param p_name
     * @param p_type
     */
    async saveToServer(p_name, p_type, tid, data_id, cpasDesc, beforeData = null) {
        const name = p_name || this.props.name;
        const type = p_type || this.props.type;
        if (!tid) {
            tid = nanoid10();
        }
        // 获取前端内存中数据
        const headers = this.headerService.headerColumn;
        const sourceData = this.hot.getSourceData();
        const displayData = this.hot.getData();
        const cellsConfig = this.filterMetas();
        const headerJson = this.headerService.headJson;
        const tableConfig = JSON.stringify(this.tableConfig);
        // 拼接IGridData数据
        let iGridData = {
            header: headerJson,
            data: sourceData,
            displayData: displayData,
            cellsMeta: cellsConfig,
            tableConfig: tableConfig,
        };
        // 进行过滤 运行时列
        iGridData = await this.filterRunTimeColumn(iGridData);
        // 过滤后的计算数据iGridData
        let { header: cHeader, data: cSourceData, displayData: cDisplayData, cellsMeta: cCellsMeta, } = iGridData;
        // 重新计算header
        const headerComputeData = this.headerService.headerComputeData(cHeader);
        const cHeaderColumn = headerComputeData.headerColumn;
        const lastHeader = headerComputeData.lastHeader;
        // 列入库数据
        const headerData = this.headerService.toServerLevelData(cHeader, tid, type);
        const rowMaps = this.gridService.getAllRowsMaps([...cSourceData]);
        const columnMaps = this.headerService.getAllHeaderMap([...cSourceData]);
        const params = {
            sourceData: cSourceData,
            displayData: cDisplayData,
            beforeData,
            rowMaps,
            columnMaps,
            headerData,
            lastHeader,
            cellsMeta: cCellsMeta,
            tableConfig,
            headers: cHeaderColumn,
            name,
            tid,
            type,
            data_id,
            cpasDesc,
        };
        return await this.saveCpasTable(params);
    }

     async saveToServerAllData(p_name, p_type, tid, data_id, cpasDesc, beforeData = null) {
        const name = p_name || this.props.name;
        const type = p_type || this.props.type;
        if (!tid) {
            tid = nanoid10();
        }
        // 获取前端内存中数据
        const headers = this.headerService.headerColumn;
        const sourceData = this.hot.getSourceData();
        const displayData = this.hot.getData();
        const cellsConfig = this.filterMetas();
        const headerJson = this.headerService.headJson;
        const tableConfig = JSON.stringify(this.tableConfig);
        // 拼接IGridData数据
        let iGridData = {
            header: headerJson,
            data: sourceData,
            displayData: displayData,
            cellsMeta: cellsConfig,
            tableConfig: tableConfig,
        };
        // 进行过滤 运行时列
        iGridData = await this.filterRunTimeColumn(iGridData);
        // 过滤后的计算数据iGridData
        let { header: cHeader, data: cSourceData, displayData: cDisplayData, cellsMeta: cCellsMeta, } = iGridData;
        // 重新计算header
        const headerComputeData = this.headerService.headerComputeData(cHeader);
        const cHeaderColumn = headerComputeData.headerColumn;
        const lastHeader = headerComputeData.lastHeader;
        // 列入库数据
        const headerData = this.headerService.toServerLevelData(cHeader, tid, type);
        const rowMaps = this.gridService.getAllRowsMaps([...cSourceData]);
        const columnMaps = this.headerService.getAllHeaderMap([...cSourceData]);
        const params = {
            sourceData: cSourceData,
            displayData: cDisplayData,
            beforeData,
            rowMaps,
            columnMaps,
            headerData,
            lastHeader,
            cellsMeta: cCellsMeta,
            tableConfig,
            headers: cHeaderColumn,
            name,
            tid,
            type,
            data_id,
            cpasDesc,
        };
       // return await this.saveCpasTable(params);
        return params;
    }
    /**
     * 合并系统保存三表：从组件中获取数据源进行存储
     * @param p_name
     * @param p_type
     */
    async saveToServerMerge(p_name, p_type, tid, data_id, cpasDesc) {
        const name = p_name || this.props.name;
        const type = p_type || this.props.type;
        if (!tid) {
            tid = nanoid10();
        }
        // 获取前端内存中数据
        const headers = this.headerService.headerColumn;
        let sourceData = this.hot.getSourceData();
        let displayData = this.hot.getData();
        const cellsConfig = this.filterMetas();
        const headerJson = this.headerService.headJson;
        const tableConfig = JSON.stringify(this.tableConfig);
        // 拼接IGridData数据
        let iGridData = {
            header: headerJson,
            data: sourceData,
            displayData: displayData,
            cellsMeta: cellsConfig,
            tableConfig: tableConfig,
        };
        // 调整数示例
        // const iGridData1 = (
        //   await getCpasTableDataByTzTypeAPI({
        //     iGridData: testIGridData1,
        //     tzType: "tzq",  tzq ,  tzs , tzh
        //   })
        // ).data;
        // // 进行过滤 运行时列
        // iGridData = await this.filterRunTimeColumn(iGridData);
        // 过滤后的计算数据iGridData
        let { header: cHeader, data: cSourceData, displayData: cDisplayData, cellsMeta: cCellsMeta, } = iGridData;
        const fSourceData = deepClone(cSourceData);
        //合并系统合并层的法定和合并用需要做调整数的displayData和sourceData数据传入
        const rawData = this.rawData;
        // 调整前数调用
        const tzqGridData1 = (await getCpasTableDataByTzTypeAPI({
            iGridData: iGridData,
            tzType: "tzq",
        })).data;
        // 调整后数调用
        const tzhGridData1 = (await getCpasTableDataByTzTypeAPI({
            iGridData: iGridData,
            tzType: "tzh",
        })).data;
        if (tzhGridData1?.displayData) {
            cDisplayData = tzhGridData1?.displayData;
        }
        if (tzhGridData1?.data) {
            cSourceData = tzhGridData1?.data;
        }
        if (tzhGridData1?.header) {
            cHeader = tzhGridData1?.header;
        }
        if (tzhGridData1?.cellsMeta) {
            cCellsMeta = tzhGridData1?.cellsMeta;
        }
        // 进行过滤调整后 运行时列
        const newGridData = await this.filterRunTimeColumn({
            ...iGridData,
            header: cHeader,
            data: cSourceData,
            displayData: cDisplayData,
        });
        //过滤调整前运行时列
        const tzqNewGridData = await this.filterRunTimeColumn({
            ...iGridData,
            header: cHeader,
            data: tzqGridData1?.data ? tzqGridData1.data : cSourceData,
            displayData: tzqGridData1?.displayData
                ? tzqGridData1?.displayData
                : cDisplayData,
        });
        const { header: nHeaderData, data: nData, displayData: nDisplayData, } = newGridData;
        cHeader = nHeaderData;
        cDisplayData = nDisplayData;
        cSourceData = nData;
        // 重新计算header
        const headerComputeData = this.headerService.headerComputeData(cHeader);
        const cHeaderColumn = headerComputeData.headerColumn;
        const lastHeader = headerComputeData.lastHeader;
        // 列入库数据
        const headerData = this.headerService.toServerLevelData(cHeader, tid, type);
        const rowMaps = this.gridService.getAllRowsMaps([...cSourceData]);
        const columnMaps = this.headerService.getAllHeaderMap([...cSourceData]);
        const tzqHeaderComputeData = this.headerService.headerComputeData(cHeader);
        const tzqHeaderColumn = tzqHeaderComputeData.headerColumn;
        const tzqData = tzqNewGridData?.displayData
            ? tzqNewGridData?.displayData
            : cDisplayData; //调整前data
        //计算beforeData
        const beforeData = compareArrays(tzqData, rawData, tzqHeaderColumn); //前置数据: 调整前的displayData和rawData进行全表比较，生成一个数组data
        // const tzRes: any = await getDsToTZData(
        //   {
        //     data: cSourceData,
        //   },
        //   tid
        // );
        // if (tzRes?.data) {
        //   cSourceData = tzRes?.data;
        //   //重算出调整后的显示值
        //   const resDisplayData = await reCalculateNote({
        //     ...iGridData,
        //     data: cSourceData,
        //   });
        //   if (resDisplayData?.data?.displayData) {
        //     cDisplayData = resDisplayData?.data?.displayData;
        //   }
        //   // console.log(resDisplayData, "response----");
        // }
        const params = {
            sourceData: cSourceData,
            displayData: cDisplayData,
            beforeData,
            rowMaps,
            columnMaps,
            headerData,
            lastHeader,
            cellsMeta: cCellsMeta,
            tableConfig,
            headers: cHeaderColumn,
            name,
            tid,
            type,
            data_id,
            cpasDesc,
        };
        return await this.saveCpasTable(params);
    }
    //渲染重复提示
    renderRepeatTip(repeatData, noteName) {
        let dataSource = [];
        const columns = [
            {
                title: "节点名称",
                dataIndex: "noteName",
                key: "noteName",
            },
            {
                title: "重复主键",
                dataIndex: "rmap",
                key: "rmap",
            },
            {
                title: "重复行号",
                width: 150,
                dataIndex: "rowIndex",
                key: "rowIndex",
            },
            {
                title: "对应项目列",
                dataIndex: "projectName",
                key: "projectName",
                width: 300,
            },
        ];
        for (let i = 0; i < repeatData.length; i++) {
            const { repIndex, index, projectCol, key } = repeatData[i];
            dataSource.push({
                key: i,
                rmap: key,
                rowIndex: `第${index.join(",")}行重复`,
                projectName: projectCol.join(" | "),
                noteName,
            });
        }
        Modal.info({
            title: "提示",
            width: 800,
            content: (_jsxs(_Fragment, { children: [_jsxs("p", { children: [_jsx("b", { children: "\u65E0\u6CD5\u4FDD\u5B58" }), ",\u9879\u76EE\u5217\u91CD\u590D\u4E86! \u8BF7\u4FEE\u6539\u91CD\u590D\u7684\u9879\u76EE\u5217\u540D\u79F0~"] }), _jsx(Table, { dataSource: dataSource, columns: columns })] })),
            onOk() { },
        });
    }
    /**
     * 存储数据服务
     */
    async saveCpasTable(params) {
        const { tid } = params;
        let serverData = {};
        //fs｜ds表rmap重复提示
        const repeatData = this.gridService.getDataByRmapRepeat(params.displayData);
        if (repeatData && repeatData.length) {
            if (params?.type === "zl") {
                return;
            }
            this.renderRepeatTip(repeatData, params.name);
            return;
        }
        try {
            const res = await getCpasTableServerDataByJsonApi(params);
            if (res) {
                serverData = res.data;
            }
        }
        catch (e) {
            throw e;
        }
        let isVerify = null;
        if (this.articulationVerifyService.artVerifyFormulaList.length > 0 && tid) {
            isVerify = this.articulationVerifyService.getArtVerifyResult();
            serverData["isVerify"] = isVerify;
        }
        // TODO 过滤运行时展示列
        //保存表数据
        const response = await saveTableApi(serverData);
        //保存勾稽校验数据
        if (isVerify !== null) {
            const otherArtVerifyFormulaList = this.articulationVerifyService.otherArtVerifyFormulaList;
            let artVerifyFormulaList = this.articulationVerifyService.artVerifyFormulaList;
            //兼容后端，把非本表的数据透传过去
            if (otherArtVerifyFormulaList && otherArtVerifyFormulaList.length) {
                artVerifyFormulaList = artVerifyFormulaList.concat(otherArtVerifyFormulaList);
            }
            artVerifyFormulaList.map((item) => {
                item["tid"] = item.tid ? item.tid : tid;
            });
            const parentDynamicMaps = this.articulationVerifyService
                ?.parentDynamicMaps
                ? this.articulationVerifyService.parentDynamicMaps.filter((item) => item.tid !== tid)
                : null;
            console.log(parentDynamicMaps, "parentDynamicMaps-----");
            try {
                if (parentDynamicMaps && parentDynamicMaps.length) {
                    await removeVerifyDataById(parentDynamicMaps, tid);
                }
                //@todo0906bydingxiaofei合并系统编辑模版状态下暂时去掉保存勾稽校验,后面模版算开后，需要还原
                const mergeType = getHbTypeByZcbfid();
                if (mergeType !== MergeType.TEMPLATE) {
                    await saveVerifyData(tid, this.articulationVerifyService.artParseResultList, artVerifyFormulaList);
                }
            }
            catch (e) {
                throw e;
            }
        }
        else {
            //删除勾稽校验数据
            try {
                await removeVerifyData(tid);
            }
            catch (e) {
                throw e;
            }
        }
        return response.code === 200;
    }
    /**
     * 过滤提交到数据库中的config信息
     * isCellsMetaNeed , 这种情况是 this.cellsMeta信息中需要，导出json中也需要。但是不需要入数据库的情况.主要用于filterMeta中
     */
    excludeConfigToServer(configItem, isCellsMetaNeed) {
        const copyConfigItem = _.cloneDeep(configItem);
        if (copyConfigItem.source) {
            delete copyConfigItem.source;
        }
        if (isCellsMetaNeed) {
            if (copyConfigItem.beVerified) {
                delete copyConfigItem.beVerified;
            }
            if (copyConfigItem.verify) {
                delete copyConfigItem.verify;
            }
        }
        // 过滤，后台将公式存在了字段里不存config中
        if (copyConfigItem.formula) {
            delete copyConfigItem.formula;
        }
        if (copyConfigItem.formulaState) {
            delete copyConfigItem.formulaState;
        }
        return copyConfigItem;
    }
    /**
     * 设置勾稽校验数据
     */
    setVerifyData(verifyData) {
        const { artParseResultList, artVerifyFormulaItemList } = verifyData;
        this.articulationVerifyService.artVerifyFormulaList =
            artVerifyFormulaItemList;
        this.articulationVerifyService.artParseResultList = artParseResultList;
    }
    /**
     * 从线上加载勾稽校验
     */
    async loadVerifyByServer(tid) {
        if (this.props.verifyMode && tid) {
            try {
                const result = await getVerifyDataApi(tid);
                if (result.code === 200) {
                    return result.data;
                }
            }
            catch (e) {
                console.error(e);
            }
        }
        else {
            console.error("请传入tid");
        }
    }
    /**
     * 从线上加载数据对外暴露
     * @param name
     * @param data_id
     * @param tid
     * @param ptype
     * @param isNeedBeforeData 用于合并系统，是否用于A->O->C合并逻辑
     */
    async loadTableByServer(name, data_id, tid, ptype, isNeedBeforeData) {
        const type = ptype || this.props.type;
        this.dataSource = "server";
        if (!name) {
            alert("请先选择要加载的设计表");
            return;
        }
        try {
            // const res = await getDesignTableInfoByTidApi(name);
            const res = await getDesignTableInfoByNameApi(name, data_id, type, "all", "json", isNeedBeforeData);
            console.log('aaaaaaaaaaaaaaa',res);
            if (res.code === 500) {
                return res;
            }
            this.currentDataMaps = this.gridService.createMapByData(res.data.displayData);
            this.rawData = res?.data?.rawData;
            console.log("当前:currentDataMaps", this.currentDataMaps);
            this.dataFrom = "server";
            // if (isNeedBeforeData && res?.data?.beforeData) {
            //   res["data"]["data"] = res?.data?.beforeData;
            // }
            return res.data;
        }
        catch (e) {
            throw e;
        }
    }
    /**
     * 获取取数源公式
     * type : cell , row , column
     */
    getFormulaByCoords(coords, type) {
        const { row, col } = coords;
        if (row && col && type === "cell") {
            return this.hot.getSourceData()[row][col];
        }
        else if (row && col && type === "row") {
            return this.gridService.getRowMeteDataByRow(row);
        }
        else if (row && col && type === "column") {
            return this.headerService.headerColumn[col].config;
        }
        else {
            return false;
        }
    }
    /**
     * 获取所有cpas-table设计表
     */
    async getAllDesignTable(type) {
        return await getAllDesignTableApi(type);
    }
    /**
     * 删除cpas-table设计表
     * @param tid
     */
    async removeTableByServer(tname, data_id, type) {
        if (!tname) {
            alert("请先选择要删除的设计表");
            return;
        }
        try {
            const res = await removeCpasTableByName(tname, data_id, type);
            return res.data;
        }
        catch (e) {
            throw e;
        }
    }
    /**
     * 获取行列关系
     */
    getCurrentTableMaps() {
        const rmaps = this.gridService.getAllRowsMaps();
        const cmaps = this.headerService.getAllHeaderMap();
        return {
            rmaps,
            cmaps,
        };
    }
    /**
     * 根据rmap,cmap获取显示值
     */
    getCellValueByRmapCmap(rmap, cmap) {
        return this.gridService.getCellValueByRmapCmap(rmap, cmap);
    }
    /**
     * 获取当前选中列索引
     */
    getNodeIndexBySelected() {
        return this.headerService.getNodeIndexBySelected();
    }
    /**
     * 解析多个运算公式
     */
    async formulasListComputed(formulasList) {
        const resultMapList = new Map();
        try {
            for (let i = 0; i < formulasList.length; i++) {
                const formula = formulasList[i];
                // 前端时间片解析公式方式
                // const result = await this.formulaHandle(`=${formula}`);
                // 后台接口解析方式
                const result = await parseFormulaApi(`=${formula}`);
                resultMapList.set(formula, result);
            }
            return resultMapList;
        }
        catch (e) {
            throw e;
        }
    }
    /**
     *
     */
    openMenuTools() { }
    /**
     * 调用校验详情
     */
    openVerifyInfo() { }
    // ----------------------------  线上服务相关 ------------------------------
    // ----------------------------  勾稽校验    -------------------------------
    //测试勾稽公式解析
    async testVerifyFormula() {
        // const operation = "===";
        //
        // // 表间勾稽公式
        // const v = `=CP_CELL("T货币资金","库存现金","期初余额") + CP_CELL("T未审财务报表","衍生金融负债","2016QCYE") - FS_CELL("fa.mxb","1003","原值期初未审","2017")`;
        // const result_v = await this.hyperFormulaService.parseAsyncCustomFormula(
        //   v,
        //   "o"
        // );
        // console.log("校验项");
        // console.log(result_v);
        // const bv = `=IN_CELL("固定资产","期末余额") + IN_CELL("建筑物","期末余额")`;
        // const result_bv = await this.hyperFormulaService.parseAsyncCustomFormula(
        //   bv,
        //   "o"
        // );
        // console.log("被校验项");
        // console.log(result_bv);
        //
        // const result = eval(`${result_bv} ${operation} ${result_v}`);
        // console.log("校验结果");
        // console.log(result);
        // 表间校验 case1
        //IN_CELL("应收账款","期末余额") + IN_CELL("财务费用","期末余额") 3
        // CP_CELL("T货币资金|前","库存现金","期初余额","2017") = 22
        // CP_CELL("T未审财务报表","衍生金融负债","2016QCYE") = 123123
        // FS_CELL("fa.mxb","1003","原值期初未审","2017") = 1001
        //  IN_CELL("拆入资金","期初余额") 1001
        const case1 = {
            number: 1,
            type: artVerifyFormulaType.OUT_V,
            isForce: true,
            beVerifiedFormula: `IN_CELL("应收账款","期末余额") + IN_CELL("财务费用","期末余额")`,
            verifyFormula: `CP_CELL("其他流动负债| 前","应收票据坏账损失","期末余额","本年")`,
            operation: "==",
        };
        // //与报表校验 case2
        //
        const case3 = {
            number: 3,
            type: artVerifyFormulaType.FS_V,
            isForce: true,
            beVerifiedFormula: `IN_CELL("应收账款","期初余额") + IN_CELL("财务费用","期初余额")`,
            verifyFormula: `FS_CELL("base.reportItems","财务费用","账面发生额","上两年") + FS_CELL("base.reportItems","财务费用","账面期末余额","上两年")+IN_CELL("拆出资金","期初余额") + IN_CELL("拆入资金","期初余额")`,
            operation: "==",
        };
        //表内校验 case3
        const case2 = {
            number: 2,
            type: artVerifyFormulaType.IN_V,
            isForce: true,
            beVerifiedFormula: `IN_CELL("应收账款","期初余额") + IN_CELL("财务费用","期初余额")`,
            // verifyFormula: `IN_CELL("应收账款","期末余额") + IN_CELL("财务费用","期末余额")`,
            verifyFormula: `IN_CELL("拆出资金","期初余额") + IN_CELL("拆入资金","期初余额")`,
            operation: "==",
        };
        //交叉校验 case4
        const case4 = {
            number: 4,
            type: artVerifyFormulaType.CROSS_V,
            isForce: true,
            beVerifiedFormula: `V_CROSS("期初余额")`,
            verifyFormula: `V_CROSS("期末余额")`,
            operation: "==",
        };
        // const case5 = {
        //   beVerifiedFormula: 'IN_CELL("aaa","金额")',
        //   verifyFormula:
        //     'FS_CELL("base.reportItems","财务费用","账面借方发生额","2017")',
        //   operation: "==",
        //   number: 3,
        //   type: "3",
        //   isForce: true,
        // };
        // CP_CELL("T货币资金","库存现金","期初余额") + CP_CELL("T未审财务报表","衍生金融负债","2016QCYE") - FS_CELL("fa.mxb","1003","原值期初未审","2017")
        // const testSingleFormula = `= CP_CELL("T货币资金","库存现金","期初余额")`;
        // const result = await this.hyperFormulaService.parseAsyncCustomFormula(
        //   testSingleFormula,
        //   "o"
        // );
        // console.log(result);
        // let testCase = case4;
        // //
        // const result =
        //   await this.articulationVerifyService.parseArtVerifyFormulaItem(case1);
        // console.log(result);
        const formulas = [case1, case2, case3, case4];
        // //
        const result = await this.articulationVerifyService.parseArtVerifyFormula(formulas);
        //
        console.log(result);
        //测试标记服务
        //交叉校验case通过
        // const testMarkCase = result[3];
        // this.articulationVerifyService.markBeVerifiedItem(testMarkCase, true, true);
        //行内标注
        //行内标注case通过
        // const testMarkCase = result[0];
        // this.articulationVerifyService.markBeVerifiedItem(
        //   testMarkCase,
        //   false,
        //   true
        // );
        //与报表校验
        //与报表校验case通过
        // const testMarkCase = result[2];
        // this.articulationVerifyService.markBeVerifiedItem(testMarkCase, true, true);
        //与表间校验
        //表间校验case通过
        // const testMarkCase = result[0];
        // this.articulationVerifyService.markBeVerifiedItem(testMarkCase, true, true);
        //测试批量被校验项标记
        // this.articulationVerifyService.batchMarkBeVerifiedItem(result);
        const testRowData = [
            [
                "\\",
                "项目",
                "金额",
                null,
                null,
                '{"rId":"dbf78031357f4bd29017419a43970f76-key","className":"cpas-map-model","type":"autocomplete","visibleRows":10,"strict":true,"source":["","AliasItemName","CFLDFFSE","CFLDFJE","CFLJFFSE","CFLJFJE","Code","Data_ID","DFLJFSE","FX","GUID","IsEnd","IsZDZH","ItemName","JC","JFLJFSE","LJFSE","OwnerReport","PCode","QCCFLDFFSE","QCCFLDFJE","QCCFLJFFSE","QCCFLJFJE","QCLJFSE","QCQTDFFSE","QCQTDFJE","QCQTJFFSE","QCQTJFJE","QCSDLJFSE","QCSDS","QCWSLJFSE","QCWSS","QCYE","QCZBDFFSE","QCZBDFJE","QCZBHCDFFSE","QCZBHCJFFSE","QCZBJFFSE","QCZBJFJE","QCZXDFFSE","QCZXDFJE","QCZXJFFSE","QCZXJFJE","QMYE","QTDFFSE","QTDFJE","QTJFFSE","QTJFJE","QYQCYE","QYQMYE","SDDFLJFSE","SDJFLJFSE","SDLJFSE","SDS","SNS","SNSDS","SNSTZDFJE","SNSTZJFJE","SumLevel","Type","WSDFLJFSE","WSJFLJFSE","WSLJFSE","WSS","ZBDFFSE","ZBDFJE","ZBJFFSE","ZBJFJE","ZXDFFSE","ZXDFJE","ZXJFFSE","ZXJFJE"]}',
            ],
            ["", "", 10, "=C5", null, '{"rId":"2afa19ee127943d6a9f989ad06d69666"}'],
            [
                null,
                null,
                20,
                "=C6",
                null,
                '{"rId":"52201ec929804a8e8659e63a5642b6b1"}',
            ],
            [
                null,
                null,
                30,
                "=C7",
                null,
                '{"rId":"f382509cdcd1412092f919161c6c2d64"}',
            ],
            [
                null,
                null,
                "=SUM(C5,C6,C7)",
                "=SUM(C5,C6,C7)",
                null,
                '{"rId":"bc2eaaa0045645d89fba189295185ab9"}',
            ],
        ];
        const testColumnData = [
            [
                "\\",
                "项目",
                "金额",
                null,
                null,
                '{"rId":"dbf78031357f4bd29017419a43970f76-key","className":"cpas-map-model","type":"autocomplete","visibleRows":10,"strict":true,"source":["","AliasItemName","CFLDFFSE","CFLDFJE","CFLJFFSE","CFLJFJE","Code","Data_ID","DFLJFSE","FX","GUID","IsEnd","IsZDZH","ItemName","JC","JFLJFSE","LJFSE","OwnerReport","PCode","QCCFLDFFSE","QCCFLDFJE","QCCFLJFFSE","QCCFLJFJE","QCLJFSE","QCQTDFFSE","QCQTDFJE","QCQTJFFSE","QCQTJFJE","QCSDLJFSE","QCSDS","QCWSLJFSE","QCWSS","QCYE","QCZBDFFSE","QCZBDFJE","QCZBHCDFFSE","QCZBHCJFFSE","QCZBJFFSE","QCZBJFJE","QCZXDFFSE","QCZXDFJE","QCZXJFFSE","QCZXJFJE","QMYE","QTDFFSE","QTDFJE","QTJFFSE","QTJFJE","QYQCYE","QYQMYE","SDDFLJFSE","SDJFLJFSE","SDLJFSE","SDS","SNS","SNSDS","SNSTZDFJE","SNSTZJFJE","SumLevel","Type","WSDFLJFSE","WSJFLJFSE","WSLJFSE","WSS","ZBDFFSE","ZBDFJE","ZBJFFSE","ZBJFJE","ZXDFFSE","ZXDFJE","ZXJFFSE","ZXJFJE"]}',
            ],
            ["", "", 10, "=C2", null, '{"rId":"2afa19ee127943d6a9f989ad06d69666"}'],
            [
                null,
                null,
                20,
                "=C3",
                null,
                '{"rId":"52201ec929804a8e8659e63a5642b6b1"}',
            ],
            [
                null,
                null,
                30,
                "=C4",
                null,
                '{"rId":"f382509cdcd1412092f919161c6c2d64"}',
            ],
            [
                null,
                null,
                "=SUM(C2,C3,C4)",
                "=SUM(C2,C3,C4)",
                null,
                '{"rId":"bc2eaaa0045645d89fba189295185ab9"}',
            ],
        ];
        // 公式减3行 case
        // const data = HyperFormulaService.transformExcelGridData(
        //   testRowData,
        //   -3,
        //   "row"
        // );
        // console.log(data);
        //公式增加1列 case
        // const data = HyperFormulaService.transformExcelGridData(
        //   testColumnData,
        //   1,
        //   "column"
        // );
        // console.log(data);
        //公式增减1列 case
        const data = HyperFormulaService.transformExcelGridData(testColumnData, -1, "column");
        console.log(data);
    }
    /**
     * 自定义公式取数定义:
     *
     * InV[rowId,colId] 表内取数
     * OutV[rowId,colId] 表间取数
     * InF[公式别名]   公式套公式.
     * OutF[公式别名]
     *
     */
    async testCustomFormula() {
        // const formula = "([1,2] + [3,4]) * 5";
        // 1. 待确认,业务形态，设置校验的时候, 不可以在对表格结构进行编辑. 否则无论结构如何变更,都需要手动来到这里改变公式
        // 2. 用 rId,cId 来标识。对于用户来讲展现的形式从公式上不直观。就不能用公式法来标识了需要UI交互界面的设计. 通过组件data的语义化.  [rid,cid]语法
        // in / out   //:参数   //[]   rule:固定资产:rule1
        // const formula = `=FS_CELL("fa.mxb","1003","原值期初未审","2017")  +  (FS_CELL("fa.mxb","1003","原值期初未审","2017")  - FS_CELL("base.reportItems","财务费用","账面发生额","2017"))`;
        // const formula = `=(CP_CELL("测试双表存储|前","应收账款","期末余额","2017") + CP_CELL("测试双表存储|后","财务费用","期末余额","2017")) * 2`;
        const formula = `=(CP_CELL("勾稽校验","应收账款","期初余额") + CP_CELL("勾稽校验","财务费用","期末余额")) * 2`;
        const formula_parse = await this.customFormulaService.parseFormula(formula);
        const result = this.hyper.calculateFormula("=" + formula_parse, 0);
        // const result = this.customFormulaService.calcFormula(formula_parse);
        console.log(result);
    }
    // ----------------------------  勾稽校验    -------------------------------
    currentMemoryFormula() {
        console.log(HyperFormulaService.memoryMapCache);
    }
    async afterDivideTableRender(gridDataArr, extra) {
        console.log("--------------渲染拆表数据---------------");
        console.error(this);
        const zlDiv = document
            .getElementById("cpasstableWapperRef2")
            .querySelector("cpas-excel-grid-container-multiple");
        if (zlDiv) {
            zlDiv.remove();
        }
        const tableCount = gridDataArr?.length;
        const dismantleTableElementArr = [];
        const dsName = this.props.name;
        const cpasTableRefs = [];
        let timer = null;
        //计算header宽度
        // function computedHeaderWidth(header) {
        //   if (!header || !header.length) {
        //     return 0;
        //   }
        //   let w = 0;
        //   for (let i = 0; i < header.length; i++) {
        //     const width = header[i]?.config?.width;
        //     if (width) {
        //       w += width;
        //     }
        //   }
        //   w = w - 220;
        //   return w;
        // }
        for (let tableIndex = 0; tableIndex < tableCount; tableIndex++) {
            const gridData = gridDataArr[tableIndex];
            console.log(tableIndex, `gridData-${tableIndex + 1}`, gridData);
            const header = gridData?.header;
            const headerComputeData = this.headerService.headerComputeData(header);
            const headerColumn = headerComputeData.headerColumn;
            // const totalWidth = computedHeaderWidth(headerColumn);
            // 动态创建n个 CpasTable 组件并设置属性
            const name = `${dsName}-more${tableIndex + 1}`;
            // const refName =`childtable${tableIndex}`;
            //console.log(refName, 'refName111');
            const refName = `childtable${tableIndex}`;
            //const React.createRef();
            const elementProps = {
                type: "zl",
                key: tableIndex,
                index: tableIndex,
                tableIndex: tableIndex,
                // totalWidth: totalWidth,
                ref: (r) => {
                    console.log(r, "r21111");
                    if (r) {
                        return cpasTableRefs.push(r);
                    }
                },
                name: name,
                tabLevel: 3,
                tabGroup: "tab-ds-group",
                mapRowsList: [],
                numberZeroReplace: " ",
                mapColumnsList: [],
                isReadOnly: true,
                model: "read",
                isShowMenuToolBar: false,
                gridData: gridData,
                isMultipleTableMode: true,
                afterOnArtCellClick: this.props.afterOnArtCellClick,
            };
            const tableHeight = this.gridService.computerTableHeight(gridData);
            elementProps.height = tableHeight;
            console.log(extra, "extra111");
            const { titleEditorVal = "", contentEditorVal = "" } = extra ? extra : {};
            const topBar = (_jsxs("div", { className: "cpas-table-ds-bar-container", children: [_jsx("div", { className: "cpas-table-ds-title", children: _jsx("span", { children: dsName }) }), _jsx("div", { className: "cpas-table-ds-input", children: _jsx(CpasEditor, { value: titleEditorVal, disabled: true }) })] }));
            const bottomBar = (_jsx("div", { className: "cpas-table-ds-bar-container", children: _jsx("div", { className: "cpas-table-ds-input", children: _jsx(CpasEditor, { value: contentEditorVal, disabled: true }) }) }));
            // 第一表只换数据，不从新渲染 目的是留着 isShowMenuToolBar={this.state.isShowZlMenuBar}
            if (tableIndex === 0) {
                elementProps.topBar = topBar;
                elementProps.isShowMenuToolBar = false;
                // delete _this.gridRef.dsTableRef.zlTableRef.bottomBar;
                // _this.gridRef.dsTableRef.zlTableRef.current.reloadTable(gridData);
                // continue;
            }
            if (tableIndex === tableCount - 1) {
                elementProps.bottomBar = bottomBar;
            }
            const element = React.createElement(CpasTable, elementProps, null);
            dismantleTableElementArr.push(element);
        }
        ReactDOM.render(dismantleTableElementArr, document.getElementById("cpasstableWapperRef2"));
        clearTimeout(timer);
        if (!this.dismantleTableMode) {
            cpassRef = this;
        }
        this.dsTableRef?.setState({
            showDismantledTable: true,
        });
        let importDismantledTableJson = sessionStorage.importDismantledTableJson
            ? JSON.parse(sessionStorage.importDismantledTableJson)
            : undefined;
        // if (!importDismantledTableJson) {
        //   message.info("拆表完成");
        // }
        sessionStorage.preventStyleLoss = JSON.stringify(true);
        this.cpasTableRefs = [...cpasTableRefs];
        // const verifyResult = this.articulationVerifyService.artParseResultList;
        const formulaList = this.articulationVerifyService.artVerifyFormulaList;
        const parseList = await this.articulationVerifyService.parseArtVerifyFormula(formulaList);
        // 增加 单点标志值 默认 []
        const resultItem = this.articulationVerifyService.artResultItem;
        console.log(this.articulationVerifyService, "切换备注详情", this, cpasTableRefs);
        if (resultItem?.length > 0) {
            this.articulationVerifyService.markBeVerifiedItem(resultItem[0], true, true);
        }
        else if (parseList.length > 0) {
            this.articulationVerifyService.batchMarkBeVerifiedItem(transformCrossData(parseList));
        }
        //兼容整理模式第一次样式不加载的情况
        this.cpasTableRefs[0].actionType = {
            action: "load",
            index: 0,
            amount: 0,
        };
        //统计信息置空处理
        this.cpasTableRefs[0]?.setState({
            statistics: {
                avg: 0,
                sum: 0,
                count: 0,
            },
        });
        //整理模式cpastable滚动条重载优化处理
        function loadCpasTableScoll() {
            const parentDiv = document.getElementById("cpasstableWapperRef2");
            const divsToChange = parentDiv.querySelectorAll(".cpas-excel-grid-multiple");
            // 遍历所有cpastable中div元素并设置新的宽度,是整理模式的纵向向滚动条贴近表格展示(默认handsontable纵向滚动条宽度没拉满的情况下巨左展示)
            divsToChange.forEach(function (div, index) {
                const childDiv = div.querySelector(".wtHider");
                // const isScrollBar = hasScrollBar(div, childDiv); //判断表格横向是否有滚动条
                // const parentStyle = window.getComputedStyle(div);
                // const parentWidth = parentStyle.getPropertyValue("width");
                const style = window.getComputedStyle(childDiv);
                let childWidth = style.getPropertyValue("width");
                console.log(childWidth, "childWidth---", index, divsToChange.length, style);
                const childHeight = childDiv.scrollHeight;
                let nWidth = childWidth ? parseInt(childWidth) : 0;
                const parentHeight = parentDiv.scrollHeight;
                // const totalWidth = div.getAttribute("data-totalwidth");
                // if (nWidth === 0 && totalWidth) {
                //   nWidth = parseInt(totalWidth);
                // }
                if (childWidth &&
                    nWidth !== 0 &&
                    nWidth < 900 &&
                    parentHeight > 733 &&
                    childHeight > 400) {
                    div.style.width = nWidth + 6 + "px";
                }
                else {
                    div.style.width = "auto";
                }
            });
        }
        loadCpasTableScoll();
        return cpasTableRefs;
    }
    componentWillMount() {
        console.log("componentWillMount", this.props.name);
        /**
         * 拆表后清空统计数据
         */
    }
    async handleResetTable() {
        cpassRef.dismantleTableMode = false;
        // dismantleTableMode = false;
        sessionStorage.dismantleTableMode = JSON.stringify(cpassRef.dismantleTableMode);
        sessionStorage.removeItem("rule");
        delete cpassRef.tableConfig.rule;
        delete cpassRef.tableConfig.dismantleTableMode;
        let hideColumnKeyArr = sessionStorage.hideColumnKeyArr
            ? JSON.parse(sessionStorage.hideColumnKeyArr)
            : undefined;
        let hideColumnArr = sessionStorage.hideColumnArr
            ? JSON.parse(sessionStorage.hideColumnArr)
            : undefined;
        if (hideColumnKeyArr) {
            cpassRef.tableConfig.hideColumnKeyArr = hideColumnKeyArr;
            cpassRef.tableConfig.hideColumnArr = hideColumnArr;
        }
        const igridData = this.dsSourceData;
        const dsFormulaSourceData = this.props.dsTableRef.getFormulaSourceData();
        const tid = this?.props?.notes?.tid;
        const result = await getDsToZlData(igridData, cpassRef.tableConfig, dsFormulaSourceData, tid);
        if (result && result.data) {
            const resultData = result.data;
            const { zlGridData, zlDivideData } = resultData;
            await cpassRef.reloadTable(zlGridData, "zl", igridData);
            const refs = cpassRef.afterDivideTableRender(zlDivideData);
            cpassRef.menuToolRef.reductionEditorRef?.current?.setDismantleTableWindowOpen(false);
            return refs;
        }
    }
    onShowDetailsModal = () => {
        this.setState({
            isOpenDetail: !this.state.isOpenDetail,
        });
    };
    render() {
        const isMultipleTableMode = this.props.isMultipleTableMode;
        console.log(this.props.name);
        console.log(this.props.type);
        // const totalWidth = this.props.totalWidth;
        return (_jsxs(_Fragment, { children: [_jsx("canvas", { ref: this.textCanvasRef, style: { display: "none" } }), _jsx("div", { className: "zl-preview-border", style: {
                        left: this.props?.gridData?.tableConfig?.directionCfg?.direction ===
                            "horizontal"
                            ? "938px"
                            : "630px",
                        display: this.props.type === "zl" ? "block" : "none",
                    } }), _jsxs("div", { className: isMultipleTableMode
                        ? "cpas-excel-grid-container cpas-excel-grid-container-multiple"
                        : "cpas-excel-grid-container", children: [_jsxs("div", { className: isMultipleTableMode
                                ? "cpas-table-container-multiple"
                                : "cpas-table-container", children: [this.props.isShowMenuToolBar && (_jsx(HandSonGridTool, { name: this.props.name, type: this.props.type, gridRef: this, itemName: this.props.itemName, ref: this.menuToolRef, isTest: this.props.isTest, 
                                    //draftFilePath={this.props.draftFilePath}
                                    draftSheetName: this.props.draftSheetName })), _jsx("div", { className: "cpas-table-top-bar", children: this.props.topBar }), _jsx("div", { style: {
                                        height: this.props.height,
                                        display: this.props.hiddenTableContainer ? "none" : "block",
                                    }, 
                                    // data-totalWidth={totalWidth}
                                    // id={this.props.container}
                                    ref: this.containerRef, className: this.klass }), _jsx("div", { className: "cpas-table-bottom-bar", children: _jsxs("div", { className: "cpas-table-ds-bar-container", children: [_jsxs("div", { className: "cpas-table-ds-count", style: {
                                                    display: this.props.hiddenTableContainer ? "none" : "block",
                                                }, children: [_jsxs("span", { children: ["\u6570\u91CF\uFF1A", this.state.statistics.count] }), _jsxs("span", { children: ["\u5408\u8BA1\uFF1A", this.state.statistics.sum] }), _jsxs("span", { children: ["\u5E73\u5747\u6570\uFF1A", this.state.statistics.avg] })] }), this.props.bottomBar] }) })] }), _jsx(CheckDetailsModal, { isOpen: this.state.isOpenDetail, handleOpen: this.onShowDetailsModal, result: this.state.result, resultList: this.state.resultList, params: this.props })] })] }));
    }
}
export default HandSonGrid;
